rails includes multiple 2 level associations -


i have table invoices column product. products table belongs other tables such categories, suppliers etc..

in view need display:

invoice.product.category inventory.product.supplier 

i trying setup controller avoid n+1 queries.

so did:

@invoices = invoice.all.includes(product => category, product => supplier) 

i have bullet gem installed, , shows there/s n+1 query detected product => [category] , add finder::includes => [:category]

it seems considering latest of includes , ignore others. suppose syntax wrong.

how can fix it?

you didn't symbolize models.

@invoices = invoice.all.includes(:product => :category, :product => :supplier) 

this can shortened using array:

@invoices = invoice.all.includes(:product => [:category, :supplier]) 

it's idiomatic put .where or .limit (or .all) @ end:

@invoices = invoice.includes(:product => [:category, :supplier]).all 

why not make 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 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -