问题
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