我有一个嵌套资源的Rails应用程序,例如:
resources :product do
resources :sales
end
在 Sale 属于 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模型中,以便在生成URL时,
link_to
(或url_for
)自动添加“父级”(在本例中为产品)?我尝试查看{{link1:
url_for
的实现}},我认为我可以通过monkeypatching HelperMethodBuilder.url.handle_model_call
来完成,但如果有其他方法,我宁愿不这样做。