Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails routes, url and subdomains

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

like image 725
bl0b Avatar asked Feb 03 '14 20:02

bl0b


People also ask

How do I see all routes in Rails?

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 many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.

How do Rails routes work?

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

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.

like image 161
Michael Lawrie Avatar answered Oct 13 '22 02:10

Michael Lawrie