我有一个带有 PRODUCT 列的表格发票。产品表则属于其他表,例如类别、供应商等。
在我看来,我需要显示:
invoice.product.CATEGORY
inventory.product.SUPPLIER
我正在尝试设置我的 Controller 以避免 n+1 查询。
所以我做了:
@invoices = Invoice.all.includes(product => category, product => supplier)
我安装了 bullet gem,它显示检测到 n+1 查询
Product => [category]
和 Add to your finder::includes => [:category]
似乎只考虑最新的包含内容而忽略其他内容。我想我的语法是错误的。
我该如何解决?
最佳答案
你没有符号化你的模型。
@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
为什么不做一个范围?
Controller
def index
@invoices = Invoice.with_details.all
end
型号
class Invoice
# ...
def self.with_details
includes(:product => [:category, :supplier])
end
end
更好的是:
Controller
def index
@invoices = Invoice.with_details(params[:qty])
end
型号
class Invoice
# ...
def self.with_details(num)
includes(:product => [:category, :supplier]).limit(num)
end
end
关于ruby-on-rails - rails 包括多个 2 级关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40570792/