8

所以我想让Rails为我处理特定于语言环境的路由。Rails路由的范围是“locale”和浅层嵌套资源

/en/companies 
/nl/companies 

与路由定义的伟大工程:

scope "(:locale)", :locale => /en|nl/ do 
    resources :companies 
end 

但同时公司有浅嵌套的资源,就像这样:

scope "(:locale)", :locale => /en|nl/ do 
    resources :companies, :shallow => true do 
    resources :pages 
    end 
end 

这使得像/en/companies/1/pages路径,但不像/en/pages/1/edit这样的路径。由于“浅”也剥离了路径的“区域”部分,所以似乎我坚持使用/pages/1/edit?locale=en。难道没有办法让Rails通过使用区域设置来处理浅层嵌套资源吗?我可以使用/en/pages/1/edit

回答

14

啊,是的!我在the API documentation找到答案。神奇的是在:shallow_path关键字,并在上面的例子中它的工作原理是这样:

scope :path => "(:locale)", :shallow_path => "(:locale)", :locale => /en|nl/ do 
    resources :companies, :shallow => true do 
    resources :pages 
    end 
end 

现在像/en/pages/1/edit作品完美的网址!

3

非常感谢Pascal,这对我非常有用。当我设置我的嵌套资源时,我注意到了类似的行为。

我会添加一些东西,使用浅语句而不是参数的块语句的选项。现在使用你给出的语法,只有直接后代(:页面)会很浅。

万一要嵌套一个更深一层(让我们跳过这个是否是最佳做法或没有参数),使用浅块将进行深如必要的浅薄:

resources :users do 
    shallow do 
    resources :categories do 
     resources :sections do 
     resources :pages 
     end 
    end 
    resources :news 
    end 
end 

下面是可用的路线助手的一个示例,您可以获得所有嵌套在其中的资源:用户

new_category_section GET (/:locale)(/:locale)/categorys/:category_id/sections/new(.:format)  {:locale=>/fr|en/, :action=>"new", :controller=>"sections"} 
edit_section   GET (/:locale)(/:locale)/sections/:id/edit(.:format)      {:locale=>/fr|en/, :action=>"edit", :controller=>"sections"} 
section    GET (/:locale)(/:locale)/sections/:id(.:format)       {:locale=>/fr|en/, :action=>"show", :controller=>"sections"} 
         PUT (/:locale)(/:locale)/sections/:id(.:format)       {:locale=>/fr|en/, :action=>"update", :controller=>"sections"} 
         DELETE (/:locale)(/:locale)/sections/:id(.:format)       {:locale=>/fr|en/, :action=>"destroy", :controller=>"sections"} 

    section_pages  GET (/:locale)(/:locale)/sections/:section_id/pages(.:format)    {:locale=>/fr|en/, :action=>"index", :controller=>"pages"} 
         POST (/:locale)(/:locale)/sections/:section_id/pages(.:format)    {:locale=>/fr|en/, :action=>"create", :controller=>"pages"} 
new_section_info_page GET (/:locale)(/:locale)/sections/:section_id/pages/new(.:format)   {:locale=>/fr|en/, :action=>"new", :controller=>"pages"} 
     dit_info_page GET (/:locale)(/:locale)/pages/:id/edit(.:format)       {:locale=>/fr|en/, :action=>"edit", :controller=>"pages"} 
      info_page GET (/:locale)(/:locale)/pages/:id(.:format)        {:locale=>/fr|en/, :action=>"show", :controller=>"pages"} 
         PUT (/:locale)(/:locale)/pages/:id(.:format)        {:locale=>/fr|en/, :action=>"update", :controller=>"pages"} 
         DELETE (/:locale)(/:locale)/pages/:id(.:format)        {:locale=>/fr|en/, :action=>"destroy", :controller=>"pages"} 
+0

有趣的见解奥利维尔。谢谢! –

+0

感谢Olivier为您的“浅做”小费!这正是我正在寻找的... – jgpawletko