Tutorial :Rails: Pass association object to the View


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?


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.


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


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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »