Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails includes multiple 2 level associations

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/s a 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?

like image 536
catmal Avatar asked Mar 01 '26 08:03

catmal


1 Answers

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
like image 97
Eric Avatar answered Mar 03 '26 02:03

Eric