Rails:将关联对象传递给View

时间:2010-05-19 06:21:59

标签: ruby-on-rails

模型Item belongs_to User

在我的控制器中,我有这样的代码:

@items = Item.find(:all)

我需要为View模板中的每个项目设置相应的用户模型。

它在控制器中工作(但不在View模板中):

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

但手动循环只是为View模板建立关联有点气味。 我怎么能不以令人毛骨悚然的方式做到这一点?

2 个答案:

答案 0 :(得分:2)

使用:include选项查找:

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

请务必阅读associations下的热切加载部分,以便在合并时不会进行大量的数据库查找。

答案 1 :(得分:0)

尝试以下内容。 只是例子

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