Rails - 如何在加载父项时按条件加载嵌套属性?

时间:2017-07-08 07:56:41

标签: ruby-on-rails rails-activerecord ruby-on-rails-5 rails-models

我有两个模型,即发票 InvoiceDetails 发票包含许多invoiceDetails。

现在,当我加载发票时,它还会按关联加载 invoiceDetails 属性。 invoiceDetails 模型的属性为 is_hide ,我想在加载发票时加载这些嵌套属性其中is_hide = 0, 强>

发票控制器:

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

这是我加载发票的方式:

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

如何在Rails 5中完成?

1 个答案:

答案 0 :(得分:0)

假设您正在执行show操作,可以添加where子句,例如

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