I have a table invoices with a column PRODUCT. Products table then belongs to other tables such as categories, suppliers etc..
In my view I need to display:
invoice.product.CATEGORY
inventory.product.SUPPLIER
I am trying to setup my controller to avoid n+1 queries.
So I did:
@invoices = Invoice.all.includes(product => category, product => supplier)
I have bullet gem installed, and it shows that there/sa n+1 query detected Product => [category]
and Add to your finder::includes => [:category]
It seems considering only the latest of the includes and ignore the others. I suppose my syntax is wrong.
How can I fix it?
You didn't symbolize your models.
@invoices = Invoice.all.includes(:product => :category, :product => :supplier)
This can be shortened by using an array:
@invoices = Invoice.all.includes(:product => [:category, :supplier])
It's idiomatic to put your .where
or .limit
(or .all
) at the end:
@invoices = Invoice.includes(:product => [:category, :supplier]).all
Why not make a scope?
controller
def index
@invoices = Invoice.with_details.all
end
model
class Invoice
# ...
def self.with_details
includes(:product => [:category, :supplier])
end
end
Even better:
controller
def index
@invoices = Invoice.with_details(params[:qty])
end
model
class Invoice
# ...
def self.with_details(num)
includes(:product => [:category, :supplier]).limit(num)
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.