我有一个客户和发票模型。一个客户有很多发票,一张发票属于一个客户。一张发票有很多发票项目,发票项目属于一个发票
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
has_many :invoice_items
accepts_nested_attributes_for :invoice_items
end
发票项目模型
class InvoiceItem < ActiveRecord::Base
belongs_to :invoice
attr_accessible :amount, :description, :rate, :tax_amount
end
我为发票创建了一个索引页面,我想在其中列出所有发票及其相应的项目,但是我面临的挑战是如何访问发票项目中的金额并将其显示在索引页面中
应用程序/视图/index.html.erb
<div class="row">
<div class="span12">
<table class="table table-striped">
<thead>
<tr>
<th>Invoice ID </th>
<th>Customer Name </th>
<th>Invoice Date </th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<% @invoices.each do |invoice| %>
<tr>
<td><%= link_to invoice.id, invoice_path(invoice) %></td>
<td><%= invoice.customer.name %></td>
<td><%= invoice.invoice_date %></td>
<td><%= invoice.invoice_items.amount %></td>
</tr>
<% end %>
</tbody>
</table>
<div class="form actions">
<p>
<%= link_to t('.new', :default => t("helpers.links.new")),
new_invoice_path, :class => 'btn btn-primary' %>
</p>
</div>
</div>
</div>
invoice.invoice_items.amount 不会从该发票的 Invoice_items 返回该金额。有任何想法吗?
下面是我的 Invoices_controller 索引方法
class InvoicesController < ApplicationController
before_filter :authenticate_user!
def index
@invoices = Invoice.includes(:customer, :invoice_items).all
end
end