首页 文章

Rails:嵌套资源的路由助手

提问于
浏览
6

我有嵌套资源如下:

resources :categories do
  resources :products
end

根据Rails Guides

您还可以将url_for与一组对象一起使用,Rails将自动确定您想要的路线:<%= link_to'广告详情',url_for([@ magazine,@ ad])%>
在这种情况下,Rails会看到@magazine是一个杂志而@ad是一个广告,因此将使用magazine_ad_path助手 . 在像link_to这样的帮手中,您可以只指定对象来代替完整的url_for调用:<%= link_to'广告详情',[@ magazine,@ ad]%>
对于其他操作,您只需要将操作名称作为数组的第一个元素插入:<%= link_to'编辑广告',[:编辑,@杂志,@ ad]%>

就我而言,我有以下代码,它们功能齐全:

<% @products.each do |product| %>
  <tr>
    <td><%= product.name %></td>
    <td><%= link_to 'Show', category_product_path(product, category_id: product.category_id) %></td>
    <td><%= link_to 'Edit', edit_category_product_path(product, category_id: product.category_id) %></td>
    <td><%= link_to 'Destroy', category_product_path(product, category_id: product.category_id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

显然它有点太冗长了,我想用rails guide中提到的技巧来缩短它 .

但是,如果我更改了显示和编辑链接,如下所示:

<% @products.each do |product| %>
  <tr>
    <td><%= product.name %></td>
    <td><%= link_to 'Show', [product, product.category_id] %></td>
    <td><%= link_to 'Edit', [:edit, product, product.category_id] %></td>
    <td><%= link_to 'Destroy', category_product_path(product, category_id: product.category_id), method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

它们都不再起作用了,页面抱怨同样的事情:

NoMethodError in Products#index
Showing /root/Projects/foo/app/views/products/index.html.erb where line #16 raised:

undefined method `persisted?' for 3:Fixnum

我错过了什么?

2 回答

  • 5

    Rails的方式是'automagically'知道使用哪个路径是通过检查为其类传递的对象,然后查找名称匹配的控制器 . 因此,您需要确保传递给 link_to 帮助器的是实际的模型对象,而不是像 category_id 那样只是 fixnum ,因此没有关联的控制器 .

    <% @products.each do |product| %>
      <tr>
        <td><%= product.name %></td>
        <td><%= link_to 'Show', [product.category, product] %></td>
        <td><%= link_to 'Edit', [:edit, product.category, product] %></td>
        <td><%= link_to 'Destroy', [product.category, product], method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
    
  • 4

    我猜测违规行是其中之一:

    <td><%= link_to 'Show', [product, product.category_id] %></td>
    <td><%= link_to 'Edit', [:edit, product, product.category_id] %></td>
    

    product.category_idFixnum ,并且路由无法知道随机数应该映射到 category_id .

    使用以前的URL,它们更具可读性 .

相关问题