0

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

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

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

4

1 回答 1

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>

当然,你应该@invoicescontrollers/invoices_controller.rb中声明

def index
  @invoices = Invoice.includes(:customer).all
end
于 2012-12-28T20:00:02.070 回答