我有一张包含PRODUCT列的桌面发票。产品表然后属于其他表,如类别,供应商等。
在我看来,我需要显示:
invoice.product.CATEGORY
inventory.product.SUPPLIER
我正在尝试设置我的控制器以避免n + 1次查询。
所以我做了:
@invoices = Invoice.all.includes(product => category, product => supplier)
我安装了bullet gem,它显示检测到了{n = 1} Product => [category]
和Add to your finder::includes => [:category]
似乎只考虑最新的包含而忽略其他包含。我想我的语法错了。
我该如何解决?
答案 0 :(得分:5)
你没有象征你的模特。
@invoices = Invoice.all.includes(:product => :category, :product => :supplier)
使用数组可以缩短这一点:
@invoices = Invoice.all.includes(:product => [:category, :supplier])
将.where
或.limit
(或.all
)放在最后,这是惯用的:
@invoices = Invoice.includes(:product => [:category, :supplier]).all
为什么不制作示波器?
<强>控制器强>
def index
@invoices = Invoice.with_details.all
end
<强>模型强>
class Invoice
# ...
def self.with_details
includes(:product => [:category, :supplier])
end
end
更好:
<强>控制器强>
def index
@invoices = Invoice.with_details(params[:qty])
end
<强>模型强>
class Invoice
# ...
def self.with_details(num)
includes(:product => [:category, :supplier]).limit(num)
end
end