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

ruby-on-rails – rails:有没有办法使用`link_to`自动使用嵌套

发布时间:2020-12-17 02:56:44 所属栏目:百科 来源:网络整理
导读:我有一个嵌套资源的rails应用程序,例如: resources :product do resources :salesend 销售所属的产品,如果没有产品,销售实例就不存在. 我可以使用link_to @product直接链接到产品: %= link_to @product.name,@product % 这产生了 a href="/products/3"Stra
我有一个嵌套资源的rails应用程序,例如:

resources :product do
  resources :sales
end

销售所属的产品,如果没有产品,销售实例就不存在.

我可以使用link_to @product直接链接到产品:

<%= link_to @product.name,@product %>

这产生了

<a href="/products/3">Strawberry Jam</a>

但是,如果我想为销售做类似的事情,我不能单独使用@sale.我必须参与该产品.这不起作用:

<%= link_to @sale.date,@sale %>

我必须使用这样的东西:

<%= link_to @sale.date,[@sale.product,@sale] %>

第一种情况不起作用,因为没有定义sale_path(只有product_sale_path).

我的问题是:我可以在Sale模型中添加一些东西,以便link_to(或url_for)在生成url时自动添加“parent”(在这种情况下为产品)吗?

我已经尝试过查看the implementation of url_for,我想我可以通过monkeypatching HelperMethodBuilder.url.handle_model_call来做到这一点,但如果有另一种方法,我宁愿不这样做.

解决方法

使用浅路由会通过将直接URL暴露给嵌套资源来避免您的问题吗?

resources :products do
  resources :sales,only: [:index,:new,:create]
end
resources :sales,only: [:show,:edit,:update,:destroy]

现在link_to @sale将起作用,你只需要涉及index,new,create的产品.

http://guides.rubyonrails.org/routing.html#nested-resources(向下滚动到浅层嵌套)

(编辑:李大同)

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

    推荐文章
      热点阅读