我有一个带有嵌套资源的 Rails 应用程序,例如:
resources :product do
resources :sales
end
Sale belongs_to Product
,Sale
实例不能没有产品。
我可以使用 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
)自动添加“parent”(在本例中为产品)什么时候生成 url?
我试过查看 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 (向下滚动到浅嵌套)
关于ruby-on-rails - rails : Is there a way to make nested resources work automatically with `link_to` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39913324/