Search code examples
ruby-on-railsrubyroutessubdomain

How to implement user specific sub domains in rails


I am writing a rails application where users can have their own username based subdomain like GitHub pages => USERNAME.github.io

What I have done is created a controller which parses subdomain from the request and finds the corresponding user.

def show
 @user = User.where(name: request.subdomain)
end

now how should I write my route so that I can accept any user specific subdomain and direct it to the above controller


Solution

  • Yes, you can get the subdomain in your routes and direct to your controller.

    You will get your subdomain either with a helper or in your routes with regexp. a regexp example is below

    get '/', to: 'controller#show', constraints: { subdomain: '/^[a-zA-Z]*/' }
    

    the above example should get a typical subdomain.

    you can find some good examples here in the links below. The rails cast has a very good example of routing by subdomain

    http://guides.rubyonrails.org/routing.html http://railscasts.com/episodes/221-subdomains-in-rails-3