[英]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.