【发布时间】:2021-05-05 11:35:03
【问题描述】:
我有控制器,我正在使用以下代码加载所有发票。
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
end
class 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 我在以下几行中包含客户
@invoices = Invoice.includes(:customer).all
但是我如何在其中添加地址,所以没有 N+1 查询地址出现。现在我已经修复了客户,只有两个查询来了,但我也需要在其中添加地址。
【问题讨论】:
标签: sql ruby-on-rails activerecord