Question

I started using rails today and got into a problem.

I created three classes: Item, Requisito and Video. The last two has a scaffold item:references

Then I pointed the Item class to the other two items.

class Item < ActiveRecord::Base
  attr_accessible :materia
  has_many :requisitos
  has_many :videos
end

Now, I want to print everything in.

item.name

item.requisito.type

item.video.link

So I made this code.

<h1>Listing items</h1>

<table>
  <tr>
    <th>Materia</th>
    <th>Requisitos</th>
    <th>Videos</th>
<th></th>
<th></th>
<th></th>
</tr>

<% @items.each do |item| %>
  <tr>
    <td><%= item.name %></td>
    <td>
        <% @items.requisitos.each do |requisito|%>
    <%= requisito.type %>
    <br>
    <% end %>
    </td>
<td>
    <% @items.videos.each do |video|%>
    <%= video.link %>
    <br>
    <% end %>
    </td>
   <td><%= link_to 'Show', item %></td>
   <td><%= link_to 'Edit', edit_item_path(item) %></td>
   <td><%= link_to 'Destroy', item, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New Item', new_item_path %>

As you can see, I just gave a shot on how the code should be... and as I expected, it was wrong. Can someone please point out the right way to make it?

Was it helpful?

Solution

Your nested each blocks should be iterating over item.requisitos not @items.requisitos (same for videos). So like this:

<% item.requisitos.each do |requisito|%>
  <%= requisito.type %>
  <br>
<% end %>

and

<% item.videos.each do |video|%>
  <%= video.link %>
  <br>
<% end %>

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top