Rails routes, url and subdomains

2019-06-17 08:51发布

问题:

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

回答1:

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.