ruby-on-rails - rails 包括多个 2 级关联

标签 ruby-on-rails

我有一个带有 PRODUCT 列的表格发票。产品表则属于其他表,例如类别、供应商等。

在我看来,我需要显示:

invoice.product.CATEGORY
inventory.product.SUPPLIER

我正在尝试设置我的 Controller 以避免 n+1 查询。

所以我做了:
@invoices = Invoice.all.includes(product => category, product => supplier)

我安装了 bullet gem,它显示检测到 n+1 查询 Product => [category]Add to your finder::includes => [:category]
似乎只考虑最新的包含内容而忽略其他内容。我想我的语法是错误的。

我该如何解决?

最佳答案

你没有符号化你的模型。

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

这可以通过使用数组来缩短:
@invoices = Invoice.all.includes(:product => [:category, :supplier])

把你的 .where 放在惯用的位置或 .limit (或 .all )最后:
@invoices = Invoice.includes(:product => [:category, :supplier]).all

为什么不做一个范围?

Controller
def index
  @invoices = Invoice.with_details.all
end

型号
class Invoice
  # ...
  def self.with_details
    includes(:product => [:category, :supplier])
  end
end

更好的是:

Controller
def index
  @invoices = Invoice.with_details(params[:qty])
end

型号
class Invoice
  # ...
  def self.with_details(num)
    includes(:product => [:category, :supplier]).limit(num)
  end
end

关于ruby-on-rails - rails 包括多个 2 级关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40570792/

相关文章:

ruby-on-rails - ruby 根据不同键的相同值删除散列的散列

ruby-on-rails - 如何使用 Ruby 中哈希的查询参数构造 URI

ruby-on-rails - 调试 Cucumber 步骤定义

ruby-on-rails - js 响应中的 Rails slim 模板

ruby-on-rails - 使用 RubyInstaller 1.9.1 RC2 后在 Windows 上启动 mongrel 时出错

ruby-on-rails - 如何使用 Rspec/Capybara 检查 span 标记中是否有特定的文本片段?

ruby-on-rails - 如何使用 Rspec stub 文件对象

ruby-on-rails - 通过 hotmail 与 Rails 联系进行邀请

ruby-on-rails - Ruby On Rails,Redis::CommandError: 'set' 命令的 ERR 参数数量错误

ruby-on-rails - 如何在不获取 ActionController::RoutingError 的情况下删除 Rails 中未使用的 css?