所以我想让Rails为我处理特定于语言环境的路由,例如
/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
的方式处理带有区域设置的浅层嵌套资源?
答案 0 :(得分: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
这样的网络效果很好!
答案 1 :(得分:3)
非常感谢Pascal,这对我来说非常有用。我在设置嵌套资源时注意到了类似的行为。
我会添加一些东西,使用块语句替代浅参数的选项。现在使用您提供的语法,只有直接后代(:pages)才会浅。
如果您想要更深层次地嵌套一个级别(让我们跳过关于这是否是最佳实践的争论),使用浅块会尽可能深入浅出:
resources :users do
shallow do
resources :categories do
resources :sections do
resources :pages
end
end
resources :news
end
end
以下是嵌套在其中的所有资源的可用路由助手的示例:users
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"}