[英]rails includes multiple 2 level associations
我有带有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]
似乎只考虑了最新的内容,而忽略了其他内容。 我想我的语法是错误的。
我该如何解决?
您没有象征模型。
@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.