Ruby on Rails将通配符子域路由到控制器/操作 [英] Ruby on Rails route for wildcard subdomains to a controller/action

查看:96
本文介绍了Ruby on Rails将通配符子域路由到控制器/操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以 username.users.example.com 的形式动态创建URL:

I dynamically create URLs of the form username.users.example.com:

bob.users.example.com
tim.users.example.com
scott.users.example.com

所有 *。users.example.com 请求都应转到特定的控制器/操作。如何在 routes.rb 中指定?

All of *.users.example.com requests should go to a particular controller/action. How do I specify this in routes.rb?

www的所有其他请求。 example.com 转到我的 routes.rb 文件中的常规路由列表。

All other requests to www.example.com go to the normal list of routes in my routes.rb file.

更新 :我观看了有关子域的跟踪信息并且显示了以下代码,这似乎正是我需要的代码(更改了控制器和子域):

UPDATE: I watch the railscast about subdomains and it showed the following bit of code which would seem to be exactly what I need (changed the controller and subdomain):

match '', to: 'my_controller#show', constraints: {subdomain: /.+\.users/}

问题在于它仅与根URL匹配。我需要它来匹配每个可能的URL与 *。users 子域。所以很明显,我会将其放在 routes.rb 文件的顶部。但是,如何指定全部路线?是否只是‘*’?还是'/ *'

The problem is it only matches the root URL. I need this to match EVERY possible URL with a *.users subdomain. So obviously I would put it at the top of my routes.rb file. But how do I specify a catch-all route? Is it simply '*'? Or '/*'?

推荐答案

我认为,您只需要执行以下操作:

I think, you just need to do the following :

lib Subdomain c>:

create a class Subdomain in lib :

  class Subdomain  
    def self.matches?(request)  
      request.subdomain.present? && request.host.include?('.users')
    end  
  end

并在您的路线中:

constraints Subdomain do
  match '', to: 'my_controller#show'
end

这篇关于Ruby on Rails将通配符子域路由到控制器/操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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