简体   繁体   English

rails包含多个2级关联

[英]rails includes multiple 2 level associations

I have a table invoices with a column PRODUCT. 我有带有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. 我正在尝试设置控制器以避免n + 1个查询。

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] 我已经安装了bullet gem,它表明存在/一个n + 1查询检测到Product => [category]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: 这是习惯把你的.where.limit (或.all )结尾:

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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