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
 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
4

3 回答 3

0

您可以使用
invoice.invoice_items.count
或获取任何元素的数量
invoice.invoice_items.size

于 2012-12-29T10:08:31.393 回答
0

也迭代invoice_items,在@invoices迭代器内部

<% @invoices.each do |invoice| %>
  <tr>
    <td><%= link_to invoice.id, invoice_path(invoice) %></td>
    <td><%= invoice.customer.name %></td>
    <td><%= invoice.invoice_date %></td>

    <% invoice.invoice_items.each do |invoice_item| %>
      <td><%= invoice_item.rate %></td>
      <td><%= invoice_item.amount %></td>
  </tr>
<% end %>

调整表

于 2012-12-29T10:48:19.333 回答
0
invoice.invoice_items.first.amount
于 2012-12-29T10:39:26.790 回答