rails 4.0中有多个“root to”路由

我试图让rails根据子域名转到不同的控制器#动作,这是我到目前为止在routes.rb中所拥有的。

Petworkslabs::Application.routes.draw do get '/', to: 'custom#show', constraints: {subdomain: '/.+/'}, as: 'custom_root' get '/', to: "welcome#home", as: 'default_root' end 

rake显示了我想要的正确路线

 rake routes Prefix Verb URI Pattern Controller#Action custom_root GET / custom#show {:subdomain=>"/.+/"} default_root GET / welcome#home 

但由于某种原因,我无法获得像abc.localhost:3000这样的请求来命中自定义控制器。 它总是路由它欢迎#home。 有任何想法吗? 我对rails很新,所以关于一般调试的任何提示也将受到赞赏。

编辑:我使用调试器逐步完成代码,这是我发现的

(rdb:32)request.domain“abc.localhost”(rdb:32)request.subdomain“”(rdb:32)request.subdomain.present? 假

看起来由于某种原因,rails认为子域不存在,即使它在那里。 我不知道是不是因为我正在做这个本地主机。

更新答案:

在Rails 3和4上为我工作:

 get '/' => 'custom#show', :constraints => { :subdomain => /.+/ } root :to => "welcome#home" 

由于某种原因,request.subdomain根本没有填充(我怀疑这是因为我在localhost上做了这个,我在这里打开了一个错误https://github.com/rails/rails/issues/12438 )。 这导致routes.rb中的正则表达式匹配失败。 我最终创建了自定义匹配? Subdomain的方法看起来像这样

 class Subdomain def self.matches?(request) request.domain.split('.').size>1 && request.subdomain != "www" end end 

并在routes.rb中挂钩

 constraints(Subdomain) do get '/', to: "custom#home", as: 'custom_root' end 

这似乎有效。

编辑:github问题页面中的更多信息https://github.com/rails/rails/issues/12438

@manishie的回答是对的,但如果您使用的是localhost那么您的devo环境中仍可能存在问题。 要修复它,请在config/environments/development.rb添加以下行:

 config.action_dispatch.tld_length = 0 

然后在routes.rb使用@manishie的答案:

 get '/' => 'custom#show', :constraints => { :subdomain => /.+/ } root :to => "welcome#home" 

问题是tld_length默认为1,并且当您使用localhost时没有域扩展,因此rails无法获取子域。 pixeltrix在这里解释得非常好: https : //github.com/rails/rails/issues/12438