Question

I have a Rails 3.1 multi-tenancy app with a domain that I'll call mydomain.com. With this I would like to create the following routes but keep coming unstuck

default root for www.mydomain.com and mydomain.com should go to a controller called home or similar default root for *.mydomain.com (except www) should go to a sesions/new route default root for *.mydomain.com (except www) when logged in will go to a dashboard controller or simialar

Can anyone help with a way of achieving this?

Was it helpful?

Solution

This is pretty similar to what you're looking for: http://maxresponsemedia.com/rails/setting-up-user-subdomains-in-rails-3/.

Edit

It appears that the link is now dead (which is why we should post more than just links!), but I was able to find it in the WayBackMachine. Here are the code examples that it had.

First, we define a couple of constraints for subdomains and the root domain:

# /lib/domains.rb

class Subdomain
  def self.matches?(request)
    request.subdomain.present? && request.subdomain != "www" && request.subdomain != ""
  end
end

class RootDomain
  @subdomains = ["www"]

  def self.matches?(request)
    @subdomains.include?(request.subdomain) || request.subdomain.blank?
  end
end

Then, in our routes.rb, we direct the subdomains to a websites controller, but any requests to domains related to the main site get sent to the static pages that are configured for the app.

# config/routes.rb
# a bunch of other routes...

# requiring the /lib/domains.rb file we created
require 'domains'

constraints(Subdomain) do
  match '/' => 'websites#show'
end

constraints(RootDomain) do
  match '/contact_us', :to => 'static_pages#contact'
  match '/about', :to => 'static_pages#about'
  match '/help', :to => 'static_pages#help'
  match '/news', :to => 'static_pages#news'
  match '/admin', :to => 'admin#index'
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top