我有控制器,我正在加载所有发票与以下代码。
def index
@invoices = Invoice.includes(:customer).all
end我有以下发票和客户型号
class Invoice < ApplicationRecord
belongs_to :customer
delegate :name,
:street,
:city,
:state,
:zip_code,
to: :customer,
prefix: true
endclass Customer < ApplicationRecord
has_one :address
has_many :invoices
delegate :street, :city, :state, :zip_code, to: :address
end现在在我看来,我有以下代码
%tr
= render partial: "row", locals: { data: invoice.id }
= render partial: "row", locals: { data: invoice.customer_name }
= render partial: "row", locals: { data: invoice.customer_street }
= render partial: "row", locals: { data: invoice.customer_city }
= render partial: "row", locals: { data: invoice.customer_state }
= render partial: "row", locals: { data: invoice.customer_zip_code }由于我使用的是地址,它正在执行N+1,我在下面的行中包含了customer
@invoices = Invoice.includes(:customer).all但是我如何在其中添加地址,所以不会出现地址的N+1查询。现在,我已经修复了客户,只有两个查询即将到来,但我也需要在其中添加地址。
发布于 2021-05-05 12:59:31
@invoices = Invoice.includes(customer: :address).all
给每个发票包括客户和每个客户包括地址。
https://stackoverflow.com/questions/67400486
复制相似问题