简体   繁体   中英

N+1 detected on parent of parent model

Here are my model associations:

Expense belongs_to Supplier belongs_to Concept

# For example:
"ADSL Connection and Telephone July 2" > Comcast > Internet
"Water Bill August 20" > PG&E > Water

I'm trying to list all of my expenses, and also show both the company it's paid to, and what concept they belong to.

The bullet gem is alerting me to an N+1 query and recommend I include it:

N+1 Query detected
  Supplier => [:payment_concept]
  Add to your finder: :include => [:payment_concept]

And in my controller, I already included the Supplier (for another N+1) issue, but when I try to include the :payment_concept I get an error that it's not a recognized symbol:

@expenses = Expense.all(:include => [:supplier, :payment_concept])

# In my view:
.rows
  - for expense in @expenses
    .item
      p.date.lato= expense.date_made
      p.supplier.lato= expense.supplier.name
      p.payment_concept.lato= expense.supplier.payment_concept.name
      p.payment_type.lato= expense.payment_type.name
      p.account.lato= expense.account
      p.price.lato= number_to_currency(expense.price)
      .item-actions
        = link_to '<i class="icon-remove"></i>'.html_safe, '#', class: 'small-button'

Understandable given that Expense only has a relationship with the supplier, and not directly with it's concept.

Any suggestions?

Did you try something like this?

 @expenses = Expense.all(:include => [:supplier => :payment_concept])

Edit:

For clarification, since Concept belongs to Supplier (which belongs to Expenses ), you need use a hash relationship in the includes statement.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM