6

我们有以下路线设置:

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

这给了我们这个:

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

这很好。

但是,当我们想生成带有语言环境的路由时,我们遇到了麻烦:

root_path生成/正确的。

root_path(:locale => :en)生成/?locale=en不受欢迎的 - 我们想要/en

所以,问题是,这可能吗?怎么可能?

4

1 回答 1

10

默认情况下使用 root 方法来定义顶级/路由。所以,你定义了相同的路线两次,导致第二个定义覆盖第一个!

下面是根方法的定义:

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

很明显,它使用 :root 作为命名路由。如果您想使用 root 方法,只需覆盖所需的参数。例如

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

并将其称为:

root_with_locale_path(:locale => :en)

所以,这不是错误!

于 2012-08-09T12:53:32.437 回答