关联访问列值rails

时间:2012-12-29 09:38:20

标签: ruby-on-rails ruby-on-rails-3 associations model-associations

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

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

3 个答案:

答案 0 :(得分:0)

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

invoice.invoice_items.size

答案 1 :(得分:0)

invoice.invoice_items.first.amount

答案 2 :(得分: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 %>

调整表格