Reputation: 6466
New to Rails and trying to test an association I have. I've got these three interrelated models: Animal, Order, and Line. Basically, Lines belong to Orders belong to Animals. And I want the animal show page to list all the orders associated with that animal and the line (singular, for now) associated with that order.
Here are the model files.
animal.rb:
class Animal < ActiveRecord::Base
attr_accessible :breed, :photo, :animal_type
has_many :orders
end
line.rb
class Line < ActiveRecord::Base
belongs_to :order
attr_accessible :notes, :units
end
order.rb
class Order < ActiveRecord::Base
belongs_to :animal
attr_accessible :status, :lines_attributes, :animal_id
has_many :lines
accepts_nested_attributes_for :lines
end
What I'm trying to do is show all the lines and orders associated with a given animal on the animal show view. Here's my show view
<p id="notice"><%= notice %></p>
<div class="pull-left">
<h2><span style="font-size:80%"> Animal Name: </span><%= @animal.name %></h2>
</div>
<br>
<table class="table">
<tr>
<th>Type of Animal</th>
<th>Breed</th>
<th>Photo</th>
</tr>
<tr>
<td><%= @animal.animal_type %></td>
<td><%= @animal.breed %></td>
<td><%= @animal.photo %></td>
</tr>
</table>
<br>
<h2>Associated Orders</h2>
<table class="table">
<tr>
<th>Order Number</th>
<th>Order Status</th>
<th>Line Notes</th>
<th>Line Units</th>
<tr>
<%= render 'orderlist' %>
</table>
<br>
<%= link_to 'Edit', edit_animal_path(@animal) %> |
<%= link_to 'Back', animals_path %>
And, finally, here's that orderlist helper
<% @animal.orders.each do |o| %>
<tr>
<th><%= o.id %></th>
<th><%= o.status %></th>
<th><%= o.lines.notes %></th>
<th><%= o.lines.units %></th>
</tr>
<%end%>
This throws up an error when I visit the show page, though, saying
undefined method `notes' for #<ActiveRecord::Relation:0x007f9259c5da80>
If I delete .notes, then it says the same for units. If I delete both (and leave o.lines), the page loads just fine and lists in those two table cells all the information (line id, line units, line notes) of the relevant lines. So it's definitely finding the right model object, but it's not letting me call the specific attribute.
Any idea what I'm doing wrong? Stumped. Thanks!
Upvotes: 0
Views: 55
Reputation: 5767
Look at your Order class:
class Order < ActiveRecord::Base
has_many :lines
end
And your view line:
o.lines.notes
o.lines
is currently a set of lines that belong to the Order.
As @rossta has posted while I'm typing this, you can concatenate the noted of all the lines.
Upvotes: 1
Reputation: 11494
You're calling the method "notes", (and "units") on a collection of lines associated with the order. You may be try to call those methods for each line in the order. To output the notes for each line in the view, a rough rewrite could be:
<% @animal.orders.each do |o| %>
<tr>
<th><%= o.id %></th>
<th><%= o.status %></th>
<th><%= o.lines.map(&:notes).join('. ') %></th>
<th><%= o.lines.map(&:units).join('. ') %></th>
</tr>
<% end %>
Upvotes: 1