在Rails中处理多个根路径和范围 [英] Dealing with multiple root paths and scopes in Rails

查看:99
本文介绍了在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

这很好。

但是,当我们想使用地区生成路线时,遇到麻烦:

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

root_path 生成 / 是正确的

root_path(:locale =>:en)生成 /?locale = en 这是不可取的-我们想要 / en

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

所以,问题是

推荐答案

root方法默认情况下用于定义顶级/路由。
因此,您定义了两次相同的路由,导致第二个定义覆盖第一个!

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!

这是root方法的定义:

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

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


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'

并称其为:

root_with_locale_path(:locale => :en)

所以,这不是错误!

这篇关于在Rails中处理多个根路径和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆