zurik
zurik

Reputation: 513

Show action with more than two models

I have an invoice model that has many_invoice items

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

Invoice Items Model

class InvoiceItem < ActiveRecord::Base
  belongs_to :invoice
  attr_accessible :amount, :description, :rate, :tax_amount
end

I now have a show action in my Invoices_controller

def show
@invoice = Invoice.find(params[:id])
respond_to do |format|
    format.html
end
end

I want to be able to show the invoice_items like description, tax amount and rate in the show page for the invoices however, it is giving me quite a challenge. Do I have to create a partial in there that deals with the invoice items? Below is my show page

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

Upvotes: 0

Views: 70

Answers (2)

sameera207
sameera207

Reputation: 16629

using a partial is not a must, but you could do this in either way

1 - with out a partial

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 ) with a partial

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

Upvotes: 1

cih
cih

Reputation: 1980

You could use a partial to keep things tidy but there is no reason you couldn't do this in your show view template.

<% @invoice.invoice_items.each do |item| %>
 <td><%= item.amount %></td>
 <td><%= item.description %></td>
 # etc
<% end %>

The invoice items are related to the @invoice object that you have in your view therefore you can access the invoices invoice_items.

Upvotes: 0

Related Questions