【问题标题】:Access child object's id in controller在控制器中访问子对象的 id
【发布时间】:2011-12-22 13:40:04
【问题描述】:

我有一个模型用户,它有_许多物品(一个物品属于一个用户)。我有一个显示用户页面,显示用户的信息和他所有物品的列表。我为每个用户的物品添加了一个链接以访问显示物品页面,此链接目前不起作用,因为我不知道如何访问物品的 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 新手,我一直在寻找了解如何解决这个问题的几个小时......

非常感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails-3 controller params


    【解决方案1】:

    当您通过 :collection 选项将集合传递给分部时,分部将为集合中的每个成员插入一次。

    <%= render :partial => "belonging", :collection => @belongings %>
    

    假设你有_belonging.html.erb

    当使用复数集合调用分部时,分部的各个实例可以通过以分部命名的变量访问正在呈现的集合的成员。在这种情况下,partial 为 _belonging,在 _belonging partial 中,可以引用 belongs 来获取正在渲染的实例。

    有了这个,既然你有归属变量可用,用它来引用归属。在您的部分更改中:

    <%= link_to "Show item", belonging_path %>
    

    <%= link_to "Show item", belonging_path(belonging.id) %>
    

    现在,belongings_controller.rbshow 操作将收到 属于而非用户的 id

    【讨论】:

    • 非常感谢赛义德,你拯救了我的一天!我真的很感谢你给出的完整解释,因为你可能已经注意到我有点迷茫和困惑!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多