0

我有一个Customer和Invoice Model。客户有许多发票和发票属于客户。发票有许多发票项和发票项目属于发票关联访问列值rails

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 

回答

0

可以使用
invoice.invoice_items.count

invoice.invoice_items.size

+0

我不想让invoice_items的数量,我想从上市发票时invoice_items一个给定的发票金额属性如图发票 – zurik

+0

我的索引页因此,请尝试'invoice.invoice_items.attributes.keys.count' – itsnikolay

+0

在rails控制台上尝试此操作返回NoMethodError:undefined方法'invoice_items'for# zurik

0
invoice.invoice_items.first.amount 
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 %> 

调整表

+0

尝试上面的示例显示了此错误NoMethodError:未定义的方法'invoice_items'为# zurik

+0

@zurik请在内部循环中尝试invoice.invoice_items.each – ketan