关联访问列值rails



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

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

我已经为发票创建了一个索引页,我想在其中列出所有发票及其相应的项目,但是,我面临的挑战是如何访问发票项目中的金额并将其显示在索引页

app/views/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

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

invoice.invoice_items.size

invoice.invoice_items.first.amount

@invoices迭代器内迭代invoice_items

<% @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 %>

调整表

相关内容

  • 没有找到相关文章

最新更新