我有一个模型用户,即属于某个用户(a has_many belongs_to A user)的用户。我有一个显示用户页面,显示用户的信息和他的所有财产的列表。我添加了一个链接到每个用户的归属,以访问显示归属页面,这个链接目前不起作用,因为我不知道如何访问归属的id。
用户和归属都被定义为资源,而归属不是用户的成员。
下面是这段代码:
用户显示页面包含:
<% unless @user.belongings.empty? %>
<table class="belongings" summary="User's objects and services">
<%= render @belongings %>
</table>
<%= will_paginate @belongings %>
<% end %>使用此部分:
<td class="belongings">
<span class="id"><strong>Object ID: </strong><%= belonging.id %></span><br/>
<span class="name"><strong>Name: </strong><%= belonging.name %></span><br/>
<p>
<span class="description"><strong>Description: </strong><%= belonging.description %></span>
</p>
<span class="price"><strong>Price per week: </strong><%= belonging.price %></span> <br/>
<span class="caution"><strong>Caution: </strong><%= belonging.caution %></span><br/>
<span class="timestamp">
Posted <%= time_ago_in_words(belonging.created_at) %> ago.
</span>
</td>
<td>
<%= link_to "Show item", belonging_path %>
</td>
</tr>问题是如何在归属的控制器中访问归属的id:
def show
@user = User.find(params[:id])
@belonging = @user.belongings.find(params[:id])
@title = @belonging.name
end==> :id总是指用户的id。我曾尝试使用:user_id访问用户,但出现“无法找到没有id的用户”,如果我尝试使用:belonging_id访问归属,则出现“无法找到没有id的归属”。
我知道这是基本的,但我是Rails的新手,我已经花了几个小时来了解如何解决这个问题……
非常感谢您的帮助!
发布于 2011-12-22 21:58:06
当您通过:collection选项将集合传递给partial时,将为集合中的每个成员插入一次partial。
<%= render :partial => "belonging", :collection => @belongings %>考虑到你有_belonging.html.erb。
当使用复数集合调用partial时,partial的各个实例可以访问通过以partial命名的变量呈现的集合成员。在本例中,partial是属于的,并且在_belonging partial中,您可以引用_belonging来获取正在呈现的实例。
有了这个,既然你有可用的归属变量,就用它来引用归属。在您的部分更改行中:
<%= link_to "Show item", belonging_path %>至
<%= link_to "Show item", belonging_path(belonging.id) %>现在,belongings_controller.rb的show操作将收到属于而不是用户的的的id。
https://stackoverflow.com/questions/8604693
复制相似问题