如何为多个资源使用相同的Partial?

时间:2016-09-13 00:38:15

标签: ruby-on-rails ruby-on-rails-4 twitter-bootstrap-3 erb

我正在使用表来列出从索引模板中的数据库中记录的内容,并且像往常一样,最后三个表格单元格用于显示,编辑和销毁对象的链接。

../用户/ index.html.erb

<table>
  ...
    <% @users.each do |user| %>
      <tr>
        ...
        <td><%= link_to 'Show', user %></td>
        <td><%= link_to 'Edit', edit_user_path(user) %></td>
        <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

无论如何,我试图将这些链接文本替换为一些Bootstrap的标志符号图标,然后我成功但它变得混乱所以我认为最好把它放在一个部分变量中与所有使用它的索引模板共享相同的表格布局。

../共享/ _editLinks.html.erb

<td>
  <%= link_to dist do %>
    <span class="glyphicon glyphicon-eye-open"></span>
  <% end %>
</td>
<td>
  <%= link_to send("edit_#{dist}_path(#{dist})") do %>
    <span class="glyphicon glyphicon-edit"></span>
  <% end %>
</td>
<td>
  <%= link_to dist, method: :delete, data: { confirm: 'Are you sure?' } do %>
    <span class="glyphicon glyphicon-remove"></span>
  <% end %>
</td>

然后使用以下代码行在索引表中呈现部分。将资源名称作为变量传递。

 <%= render 'editLinks', dist: user %>

然后第一个和最后一个链接似乎工作正常,但我在中间-Edit-链接时遇到了这个错误。

undefined method `edit_user_path(#<User:0x007f611ab015a8>)' for #<#<Class:0x007f611a7064d0>:0x007f611ab143b0>

您能告诉我导致此错误的原因以及如何使其发挥作用吗?

2 个答案:

答案 0 :(得分:1)

导致错误的行是因为您试图将对象视为字符串。

由于_path助手通常为snake_case,因此您可以对对象的类名使用underscore方法,如下所示:

<%= link_to send("edit_#{dist.class.name.underscore}_path", dist) do %>

正如Deepak所指出的,您也可以将dist对象作为send的第二个参数。否则,您最终会遇到类似的错误,因为您再次将对象视为可以强制转换为字符串的值。

答案 1 :(得分:0)

将param传递给以逗号分隔的路由/方法

<%= link_to send("edit_#{dist.class.name.underscore}_path", dist) do %>

send方法语法