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

时间:2013-10-04 00:50:02

标签: ruby-on-rails ruby ruby-on-rails-4

我试图让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认为子域不存在,即使它在那里。我不知道是不是因为我正在做这个本地主机。

3 个答案:

答案 0 :(得分:5)

更新答案:

在Rails 3&amp ;;上为我工作4:

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

答案 1 :(得分:1)

由于某种原因,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

中的更多信息

答案 2 :(得分:1)

@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