我有嵌套资源如下:
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 %>