Dealing with multiple root paths and scopes in Rails

*爱你&永不变心* 提交于 2019-12-10 13:39:20

问题


We have the following routes setup:

MyApp::Application.routes.draw do
  scope "/:locale" do    
    ...other routes
    root :to => 'home#index'
  end
  root :to => 'application#detect_language'
end

Which gives us this:

root      /:locale(.:format)    home#index
root      /                     application#detect_language

which is fine.

However, when we want to generate a route with the locale we hitting trouble:

root_path generates / which is correct.

root_path(:locale => :en) generates /?locale=en which is undesirable - we want /en

So, question is, is this possible and how so?


回答1:


root method is used by default to define the top level / route. So, you are defining the same route twice, causing the second definition to override the first!

Here is the definition of root method:

def root(options = {})
  options = { :to => options } if options.is_a?(String)
  match '/', { :as => :root, :via => :get }.merge(options)
end

It is clear that it uses :root as the named route. If you want to use the root method just override the needed params. E.g.

scope "/:locale" do    
  ...other routes
  root :to => 'home#index', :as => :root_with_locale
end
root :to => 'application#detect_language'

and call this as:

root_with_locale_path(:locale => :en)

So, this is not a bug!



来源:https://stackoverflow.com/questions/11882494/dealing-with-multiple-root-paths-and-scopes-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!