2011-03-28 29 views
3

随着Rails 3中嵌套的资源途径,比如下面:自动添加父模型ID嵌套资源

resources :magazines do 
    resources :ads 
end 

佣工如magazine_ad_path定义,而我必须通过这两个杂志和广告,这是不方便的,如果我只需要广告的引用:

magazine_ad_path(@ad.magazine, @ad) 

有一个很好的方式来建立一个ad_path帮手,是以@ad,并返回相应的地址,包括杂志的ID? (这也将随后允许使用link_to @adredirect_to @ad等,其中自动调用对应的模型类的ad_path帮手。)

回答

2

浅路由似乎是你在找什么。您可以实现浅嵌套如下:

resources :magazines do 
    shallow do 
    resources :ads 
    end 
end 

OR

resources :magazines, :shallow => true do 
    resources :ads 
end 

只有指数和新的行动嵌套。

使用嵌套资源往往会生成长URL,浅层嵌套有助于删除某些操作不一定需要的部分(也包含父资源路由)(因为父资源可以从持久子记录派生)。

+0

这的确是有效的,但我希望在URL中拥有杂志ID。 (在我的情况下,它实际上并不是简单的ID;我使用的是friendly_id,并且广告标识符在杂志上下文中不一定是唯一的。) – 2011-03-28 18:12:41

0

一种可能,但丑陋的解决方案是:

module RoutesHelper 
    def ad_path(ad) 
    magazine_ad_path(ad.magazine, ad) 
    end 

    def ad_url(ad) 
    magazine_ad_url(ad.magazine, ad) 
    end 

    def edit_ad_path(ad) 
    edit_magazine_ad_path(ad.magazine, ad) 
    end 

    def edit_ad_url(ad) 
    edit_magazine_ad_url(ad.magazine, ad) 
    end 

    ... 
end 

[ActionView::Base, ActionController::Base].each do |m| 
    m.module_eval { include RoutesHelper } 
end 

不幸的是,这有一个缺点,我必须定义不同的助手为_path_url因为redirect_to使用_url帮手,我必须手动编写edit_助手(也许我错过了一些;对此不确定),而且这只是简单的丑陋。

0

一个解决方案,我想在这种情况下使用的是使实例返回自己的路,就像这样:

class Ad 
    def path action=nil 
    [action, magazine, self] 
    end 
end 

然后在您的视图,你可以使用这个数组作为一个多态的路线:

link_to @ad.path 
link_to @ad.path(:edit) 

当然它也适用于redirect_to等

+0

好的方法。不过,我不认为模型是添加该方法的最佳地点。我宁愿把它放在帮助器中,甚至放在lib文件夹中的某处。 – 2011-04-06 19:12:06