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

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

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

laravel - Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id (View: F:\project\resources\views\admin\carousels\index.blade.php) -