【问题标题】:Access attribute from association从关联访问属性
【发布时间】:2012-12-28 19:50:22
【问题描述】:

我有一个客户和发票模型。一个客户有很多张发票,一张发票属于一个客户。

class Customer < ActiveRecord::Base
 attr_accessible :billing_address, :customer_currency, :email, :first_name, :last_name,    :mobile, :name, :payment_terms, :phase_type, :pays_vat
 validates_presence_of :first_name, :last_name, :mobile, :billing_address, :payment_terms,  :phase_type, :customer_currency

has_many :invoices

validates :email, 
        :presence => true,
        :uniqueness => true, 
        :email_format => true

validates :name, :mobile, :presence => true, :uniqueness => true
end

发票模型是

class Invoice < ActiveRecord::Base
belongs_to :customer
attr_accessible :approved_by, :due_date, :invoice_date, :terms, :customer_id, :customer

validates :invoice_date, presence: true
validates :due_date, presence: true
validates :customer, presence: true

我正在尝试创建一个索引页面,其中列出了系统中的所有发票,这将显示发票所属的客户名称。如何检索它并在我的模型和视图中清楚地描绘它?

【问题讨论】:

    标签: ruby-on-rails-3 model-view-controller


    【解决方案1】:

    我认为您已经创建了客户和发票控制器和视图(如果没有,请由 generate scaffold 完成)。然后在 views\invoices\index.html.erb 中列出发票:

    <table>
      <tr>
        <th>Invoice</th>
        <th>Customer/th>
      </tr>
    <% @invoices.each do |invoice| %>
      <tr>
        <td><%= invoice.num %></td>
        <td><%= invoice.customer.first_name %></td>
      </tr>
    <% end %>
    </table>
    

    当然,您应该在 controllers/invoices_controller.rb

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

    【讨论】:

    • 您可能应该使用 Invoice.includes(:customer).all 来避免在遍历发票时进行额外查询。
    • 肯定会,但如果有 10 张发票,您将必须进行 11 次 sql 查询 - 获取所有发票和每张发票 1 次(获取客户的名字)。如果您使用includes 方法,则只需进行 2 个查询。
    • 请注意,谢谢。但它会生成带有in where 条件的查询,这不是很快。您是否做过任何实验表明“包含”方法总是更好?
    • 我不会担心 IN 的性能。要点是如果没有includes 调用,sql 查询的数量会随着发票数量(N+1)的增加而增加。使用includes,您仍然只有 2 个。
    • 感谢您的输入,它确实有效,现在尝试使用包含
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多