来自关联的访问属性

时间:2012-12-28 19:50:22

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

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

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

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

1 个答案:

答案 0 :(得分:0)

我认为您已经创建了客户和发票控制器和视图(如果不是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