【问题标题】:Including table without relationship in rails在rails中包括没有关系的表
【发布时间】:2021-05-05 11:35:03
【问题描述】:

我有控制器,我正在使用以下代码加载所有发票。

  def index
    @invoices = Invoice.includes(:customer).all
  end

我有以下发票和客户模型

class Invoice < ApplicationRecord
  belongs_to :customer

  delegate :name,
           :street,
           :city,
           :state,
           :zip_code,
           to: :customer,
           prefix: true
end
class Customer < ApplicationRecord
  has_one :address
  has_many :invoices

  delegate :street, :city, :state, :zip_code, to: :address
end

现在在我看来,我有以下代码

%tr
  = render partial: "row", locals: { data: invoice.id }
  = render partial: "row", locals: { data: invoice.customer_name }
  = render partial: "row", locals: { data: invoice.customer_street }
  = render partial: "row", locals: { data: invoice.customer_city }
  = render partial: "row", locals: { data: invoice.customer_state }
  = render partial: "row", locals: { data: invoice.customer_zip_code }

当我使用地址时,它正在执行 N+1 我在以下几行中包含客户

@invoices = Invoice.includes(:customer).all

但是我如何在其中添加地址,所以没有 N+1 查询地址出现。现在我已经修复了客户,只有两个查询来了,但我也需要在其中添加地址。

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    @invoices = Invoice.includes(customer: :address).all

    每张发票包括客户,每张客户包括地址。

    【讨论】:

    • 太棒了,但customer: :address 的含义是什么,我尝试了:customer, :address,但没有成功。
    • (customer: :address)Hash。在很多地方,{} 在 ruby​​ 中是可选的。另一种写法是.includes({ :customer =&gt; :address })。检查文档以获取更多信息。 apidock.com/rails/ActiveRecord/QueryMethods/includes
    猜你喜欢
    • 2017-09-19
    • 2012-09-10
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多