[英]Rails: route helpers for nested resources
我有嵌套资源如下:
resources :categories do
resources :products
end
根据Rails指南 ,
您还可以将url_for与一组对象一起使用,Rails将自动确定您想要的路径:
<%= link_to 'Ad details', url_for([@magazine, @ad]) %>
在这种情况下,Rails会看到@magazine是一个杂志而@ad是一个广告,因此将使用magazine_ad_path助手。 在像link_to这样的帮助器中,您可以仅指定对象来代替完整的url_for调用:
<%= link_to 'Ad details', [@magazine, @ad] %>
对于其他操作,您只需要将操作名称作为数组的第一个元素插入:
<%= link_to 'Edit Ad', [:edit, @magazine, @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
我错过了什么?
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', [:edit, product.category, product] %></td>
<td><%= link_to 'Destroy', [product.category, product], method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
我猜测违规行是其中之一:
<td><%= link_to 'Show', [product, product.category_id] %></td>
<td><%= link_to 'Edit', [:edit, product, product.category_id] %></td>
product.category_id
是一个Fixnum
,并且路由不能知道随机数应该映射到category_id
。
使用以前的URL,它们更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.