加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:01:18 所属栏目:百科 来源:网络整理
导读:我有嵌套资源如下: resources :categories do resources :productsend 根据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 @magazi
我有嵌套资源如下:
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 %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读