gpt4 book ai didi

ruby-on-rails - rails : route helpers for nested resources

转载 作者:数据小太阳 更新时间:2023-10-29 07:04:37 26 4
gpt4 key购买 nike

我有如下嵌套资源:

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:

<%= link_to 'Ad details', url_for([@magazine, @ad]) %>

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:

<%= link_to 'Ad details', [@magazine, @ad] %>

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

<%= 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 指南中的技巧来缩短它。

但是如果我按如下方式更改显示编辑链接:

<% @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 “自动”知道使用哪条路径的方式是检查您为其类传递的对象,然后寻找名称匹配的 Controller 。因此,您需要确保传递给 link_to 帮助程序的是实际的模型对象,而不是像 category_id 这样的东西,它只是一个 fixnum,因此没有关联的 Controller 。

<% @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 %>

关于ruby-on-rails - rails : route helpers for nested resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802919/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com