Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Routing subdomain to a resource

Is it possible to map a subdomain to a resource? I have a company model. Currently, using subdomain_fu, my routing file contains:

map.company_root  '', :controller => 'companies', :action => 'show',
                      :conditions => { :subdomain => /.+/ }

My Company model contains a "subdomain" column.

Whilst this works as intended, it's a named route and isn't restful. Essentially, I need to map "name.domain.com" to the show action for the companies controller. Is a named route the way to go, or can I use a resource route?

like image 653
Homar Avatar asked Aug 19 '09 14:08

Homar


People also ask

What is routes RB in Rails?

rb . The Rails router recognises URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views. Let's consider an application to book rooms in different Hotels and take a look at how this works.

What is the difference between resources and resource in Rails?

Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.

What is Tld_length?

The tld_length parameter is used in splitting HOST into domain and subdomain components. Unfortunately, @@tld_length is used in other functions, so to be thread safe you would have to find and rewrite all those functions as well as provide thread-local storage.


1 Answers

One can pass conditions to a resource route as well as a named route. In an application I am involved with everything is scoped to an account. A :before_filter loads the account using the subdomain. Thus for resources scoped to an account, we want to scope the routes to urls with subdomains. The DRY way to do this is to use map with options:

  map.with_options :conditions => {:subdomain => /.+/} do |site|
    site.resources :user_sessions, :only => [:new, :create, :destroy]
    site.resources :users
    site.login 'login', :controller => "user_sessions", :action => "new"
    site.logout 'logout', :controller => "user_sessions", :action => "destroy"
    …
  end

  map.connect 'accounts/new/:plan', :controller => "accounts", :action => "new"
  map.resources :accounts, :only => [:new, :create]

As you can see a named route will accept a conditions hash with a subdomain too. You can also adopt the approach Ryan illustrated above or you can specify conditions on a per resource basis:

  map.resources :users, :conditions => {:subdomain => /.+/}
like image 124
Steve Graham Avatar answered Sep 25 '22 02:09

Steve Graham