自动在嵌套资源中添加父模型ID [英] Automatically add parent model id in nested resources
问题描述
在Rails 3中具有嵌套的资源路由,例如:
With nested resource routes in Rails 3, such as the following:
resources :magazines do
resources :ads
end
定义了诸如magazine_ad_path
之类的
helper,我必须同时向其传递杂志和广告,如果仅引用广告,这将很不方便:
helpers such as magazine_ad_path
are defined, to which I have to pass both a magazine and the ad, which is inconvenient if I just have a reference to the ad:
magazine_ad_path(@ad.magazine, @ad)
是否有一种很好的方法来设置一个ad_path
辅助程序,该辅助程序使用@ad
并返回包括杂志ID在内的适当地址? (这也将允许使用link_to @ad
,redirect_to @ad
等,它们会自动调用与模型类相对应的ad_path
帮助器.)
Is there a nice way to set up an ad_path
helper that takes the @ad
and returns the appropriate address including the magazine ID? (This would also then allow the use of link_to @ad
, redirect_to @ad
, etc., which automatically call the ad_path
helper corresponding to the model class.)
推荐答案
浅层路由似乎是您想要的.您可以按以下方式实现浅层嵌套:
Shallow Routing seems to be what you're looking for. You can implement shallow nesting as below :
resources :magazines do
shallow do
resources :ads
end
end
OR
resources :magazines, :shallow => true do
resources :ads
end
仅嵌套索引和新操作.
Only the index and the new actions are nested.
使用嵌套资源往往会生成较长的URL,浅层嵌套有助于删除某些操作不必要的部分(也包含父资源路由)(因为可以从持久性子记录中获取父资源)
Using nested resources tends to generate long URLs, shallow nesting helps remove parts (that contain the parent resource route as well) that aren't necessarily required for certain actions(since a parent resource can be derived from a persisted child record).
这篇关于自动在嵌套资源中添加父模型ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!