Mah*_*amy 5 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)
rake显示了我想要的正确路线
rake routes
Prefix Verb URI Pattern Controller#Action
custom_root GET / custom#show {:subdomain=>"/.+/"}
default_root GET / welcome#home
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,我无法获得像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"
Run Code Online (Sandbox Code Playgroud)
由于某种原因 request.subdomain 根本没有被填充(我怀疑这是因为我在本地主机上执行此操作,我在这里打开了一个错误https://github.com/rails/rails/issues/12438)。这导致routes.rb 中的正则表达式匹配失败。我最终创建了自定义匹配?子域的方法看起来像这样
class Subdomain
def self.matches?(request)
request.domain.split('.').size>1 && request.subdomain != "www"
end
end
Run Code Online (Sandbox Code Playgroud)
并将其连接到routes.rb中
constraints(Subdomain) do
get '/', to: "custom#home", as: 'custom_root'
end
Run Code Online (Sandbox Code Playgroud)
这似乎有效。
编辑:更多信息请参见 github 问题页面https://github.com/rails/rails/issues/12438
归档时间: |
|
查看次数: |
7537 次 |
最近记录: |