Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails route for wildcard subdomains to a controller/action

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

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

All of *.users.example.com requests should go to a particular controller/action. How do I specify this in 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/}

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 '/*'?

like image 732
at. Avatar asked Oct 14 '13 11:10

at.


People also ask

How do I use wildcard subdomain?

In the Subdomain field, place an asterisk * symbol there signifying that you are creating a wildcard subdomain. Choose the domain you want to create a wildcard subdomain for in the Domain section. The Document Root field will automatically generate a path for your wildcard subdomain.

How do I find a specific route in Rails?

Decoding the http request TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

How do routes work in Ruby on Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.


1 Answers

I think, you just need to do the following :

create a class Subdomain in lib :

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

and in your routes :

constraints Subdomain do
  match '', to: 'my_controller#show'
end
like image 190
Amit Thawait Avatar answered Sep 19 '22 14:09

Amit Thawait