views:

22

answers:

2

Model Item belongs_to User.

In my controller I have code like this:

@items = Item.find(:all)

I need to have a corresponding User models for each item in my View templates.

it works in controller(but not in View template):

@items.each { |item| item.user }

But manual looping just to build associations for View template kinda smells. How can I do this not in a creepy way?

+1  A: 

Use the :include option for find:

@items = Item.find(:all, :include => :user)

Be sure to read the eager loading section under associations so you're not doing a bunch of database lookups when they can be combined.

Awgy
A: 

Try something like following. Just example

<table>
  <tr>
    <td>Item Name</td>
    <td>User Name</td>
  </tr>
<% for item @items %>
   <tr>
     <td><%= item.item_name %></td>
     <td><%= item.user.name %></td>
   </tr>
<% end %>

OR

<table>
  <tr>
    <td>Item Name</td>
    <td>User Name</td>
  </tr>
<% @items.each { |item| %>
   <tr>
     <td><%= item.item_name %></td>
     <td><%= item.user.name %></td>
   </tr>
<% } %>
Salil