1

I have two models namely Invoice and InvoiceDetails. An invoice has many invoiceDetails.

Now when I load an invoice, it also loads up the invoiceDetails attributes by association. The invoiceDetails model has an attribute is_hide, I want to load these nested attributes where is_hide = 0, while loading an invoice.

The Invoice Controller:

class Api::V1::InvoicesController < ApplicationController
  respond_to :json

  def index
    company_id = params[:company_id]
    if company_id
      invoices = Invoice.where(company_id: company_id)
      render json: invoices, status: 200
    else
      render json: { errors: "Company ID is NULL" }, status: 422
    end
  end

  def show
    cust_id = params[:customer_id]
    invoice_id = params[:id]
    if cust_id && invoice_id
      invoice = Invoice.where(:id => invoice_id, :customer_id => cust_id)
      render json: invoice, include: '**', status: 200
    else
      render json: { errors: "Customer ID or Invoice ID is NULL" }, status: 422
    end
  end

  def create
    Rails.logger.debug invoice_params.inspect
    invoice = Invoice.new(invoice_params)
    if invoice.save
      render json: invoice, status: 201
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def update
    invoice_id = params[:id]
    invoice = Invoice.find(invoice_id)
    if invoice.update(invoice_params)
      render json: invoice, status: 200
    else
      render json: { errors: invoice.errors }, status: 422
    end
  end

  def invoice_params
    invoice_params = params.require(:invoice).permit(:total_amount,:balance_amount, :customer_id, :totalTax, :totalDiscount, :bill_date,:company_id, { invoice_details: [:id,:invoice_id,:product_id,:quantity, :discount, :subtotal, :tax] })
    invoice_params[:invoiceDetails_attributes] = invoice_params.delete :invoice_details
    invoice_params.permit!
  end
end

This is how I load an invoice :

getInvoice : {
        url:'/api/v1/companies/:company_id/customers/:customer_id/invoices/:id',
        method: 'GET',
        isArray: true
      }

How can this be done in Rails 5?

Paras
  • 3,191
  • 6
  • 41
  • 77

1 Answers1

0

Assuming it is the show action that you are hitting, you can add a where clause like

def show
  cust_id = params[:customer_id]
  invoice_id = params[:id]
  if cust_id && invoice_id
    invoice = Invoice.includes(:invoice_details).where(:id => invoice_id, :customer_id => cust_id, 'invoice_details.is_hide' => 0)
    render json: invoice, include: '**', status: 200
  else
    render json: { errors: "Customer ID or Invoice ID is NULL" }, status: 422
  end
end
Md. Farhan Memon
  • 6,055
  • 2
  • 11
  • 36