Rails routes, url and subdomains
Yes, you can specify a subdomain as a constraint, e.g.
get 'photos', constraints: {subdomain: 'admin'}
Check out the rails guide on the subject: http://guides.rubyonrails.org/routing.html#request-based-constraints
To link to a specific subdomain, you can specify it in a URL route helper. For example, home_url(subdomain: 'pro')
might redirect to http://pro.example.com/home
. Take care to use the _url
suffixed methods as home_path
will not redirect to a specific subdomain.
Related videos on Youtube
bl0b
Updated on July 18, 2022Comments
-
bl0b almost 2 years
My ruby app is divided in different namespaces. like: free(free.domain.com), pro(pro.domain.com), vip(vip.domain.com) In the routes file looks like this:
namespace :free do match 'home' => 'free#home', :via => [:get, :post], :as => :home #more routes end namespace :pro do match 'home' => 'pro#home', :via => [:get, :post], :as => :home #more routes end namespace :vip do match 'home' => 'vip#home', :via => [:get, :post], :as => :home #more routes end match '/about' => 'pages#about' match '/team' => 'pages#team' match '/press' => 'pages#press' #more routes
I would like that wherever I am in the app when there is a link like pro_home_path, the url be pro.domain.com/home.
So basically, is it possible in the routes file to add a subdomain(something like this
namespace :vip, :subdomain => vip do
) to append the subdomain to the corresponding namespace?EDIT: So I have added a
constraint constraints(:subdomain => "newsfeed") do
But the link when I do pro_home_path, I'm getting lvh.me/3000/pro/home instead of pro.lvh.me:3000/home
-
bl0b about 10 yearsI edited my post with a constrain but it doesn't redirect to a subdomain.
-
Michael Lawrie about 10 yearsI have updated the answer to include a solution to that. I don't believe there is a 'prettier' way to do it without writing your own helpers or finding a gem that does this.