我有一个包含许多y_invoice项的发票模型
class Invoice < ActiveRecord::Base
belongs_to :customer, :inverse_of => :invoices
attr_accessible :approved_by, :due_date, :invoice_date, :reading_ids, :terms, :customer_id, :customer, :status
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
我现在在我的Invoices_controller
中有一个显示动作def show
@invoice = Invoice.find(params[:id])
respond_to do |format|
format.html
end
end
我希望能够在发票的显示页面中显示invoice_items,如描述、税额和税率,但是,这给我带来了相当大的挑战。我需要在里面创建一个部分来处理发票项目吗?下面是我的show页面
<p id="notice"><%= notice %></p>
<div class="row">
<div class="span12">
<h3> Customer Invoices </h3>
<table class="table table-striped">
<thead>
<tr>
<th>Invoice ID </th>
<th>Customer Name </th>
<th>Invoice Date </th>
<th>Due Date </th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td><%= @invoice.customer.name %></td>
<td><%= @invoice.invoice_date %></td>
<td><%= @invoice.due_date %></td>
</tr>
</tbody>
</table>
</div>
</div>
不是必须使用partial,但您可以使用两种方法
1 -不包含部分
in your show.html.erb
#your invoice code
<% invoice_items = @invoice.invoice_items %>
<% invoice_items.each to |invoice_item|%>
<tr>
<td><%= invoice_item.amount%></td>
</tr>
<% end %>
2)与部分
in your show.html.erb
#your invoice code
<% invoice_items = @invoice.invoice_items %>
<% invoice_items.each to |invoice_item|%>
<tr>
<td>
<%= render :partial => 'invoice_item', :locals => {:item => invoice_item}%>
</td>
</tr>
<% end %>
in your _invoice_item.html.erb
<%= item.name %>
HTH
你可以使用局部来保持整洁,但是你也可以在你的显示视图模板中这样做。
<% @invoice.invoice_items.each do |item| %>
<td><%= item.amount %></td>
<td><%= item.description %></td>
# etc
<% end %>
发票项与您视图中的@invoice
对象相关,因此您可以访问发票invoice_items
。