rails 4.0 中的多个“根到"路由 [英] Multiple 'root to' routes in rails 4.0
问题描述
我正在尝试根据子域让 rails 转到不同的 controller#action,这就是我目前在 routes.rb 中的内容
I am trying to get rails to go to different controller#action according to the subdomain, and this is what I have so far in 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 shows the correct routes I want it to take
rake routes
Prefix Verb URI Pattern Controller#Action
custom_root GET / custom#show {:subdomain=>"/.+/"}
default_root GET / welcome#home
但由于某种原因,我无法获得像 abc.localhost:3000 这样的请求来命中自定义控制器.它总是将它路由到welcome#home.有任何想法吗?我对 Rails 还很陌生,所以任何关于一般调试的提示也将不胜感激.
But for some reason, I can't get requests like abc.localhost:3000 to hit the custom controller. It always routes it to welcome#home. Any ideas? I am fairly new to rails, so any tips about general debugging would also be appreciated.
我使用调试器逐步完成代码,这就是我发现的
I stepped through the code using the debugger and this is what I found
(rdb:32) request.domainabc.localhost"(rdb:32) request.subdomain"(rdb:32) request.subdomain.present?假
(rdb:32) request.domain "abc.localhost" (rdb:32) request.subdomain "" (rdb:32) request.subdomain.present? false
看起来由于某种原因 rails 认为子域不存在,即使它在那里.我想知道是不是因为我在做这个本地主机.
Looks like for some reason rails thinks that the subdomain is not present, even though its there. I wonder if its because I am doing this localhost.
推荐答案
由于某种原因 request.subdomain 根本没有被填充(我怀疑这是因为我在 localhost 上做了这个,我在这里打开了一个错误
For some reason request.subdomain was not getting populated at all (I suspect this is because I have doing this on localhost, I have opened a bug here https://github.com/rails/rails/issues/12438). This was causing the regex match in routes.rb to fail. I ended up creating a custom matches? method for Subdomain which looks something like this
class Subdomain
def self.matches?(request)
request.domain.split('.').size>1 && request.subdomain != "www"
end
end
并将其连接到 routes.rb
and hooking that up in routes.rb
constraints(Subdomain) do
get '/', to: "custom#home", as: 'custom_root'
end
这似乎有效.
github 问题页面中的更多信息 https://github.com/rails/rails/issues/12438
More information in the github issues page https://github.com/rails/rails/issues/12438
这篇关于rails 4.0 中的多个“根到"路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!