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 '/*'
?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With