ruby-on-rails – 在Rails中处理多个根路径和范围

我们有以下路线设置:

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

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

解决方法

认情况下,root方法用于定义顶级/路由.
所以,你要两次定义相同的路由,导致第二个定义覆盖第一个

以下是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)

所以,这不是一个错误

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...