ruby-on-rails – Rails:嵌套资源的路由助手

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails:嵌套资源的路由助手前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有嵌套资源如下:
resources :categories do
  resources :products
end

根据Rails Guides,

You can also use url_for with a set of objects,and Rails will automatically determine which route you want:

06001

In this case,Rails will see that @magazine is a Magazine and @ad is an Ad and will therefore use the magazine_ad_path helper. In helpers like link_to,you can specify just the object in place of the full url_for call:

06002

For other actions,you just need to insert the action name as the first element of the array:

06003

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

<% @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_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',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

我错过了什么?

解决方法

Rails“自动”知道使用哪条路径的方法是检查为其类传递的对象,然后查找名称匹配的控制器.因此,您需要确保传递给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',product.category,product] %></td>
    <td><%= link_to 'Destroy',product],data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
原文链接:https://www.f2er.com/ruby/265237.html

猜你在找的Ruby相关文章