Skip to main content

Multi Site in Rails

Rails • Asked by rabin prithvi

Have a Rails app which acts as a API client.
Request may come from 6 different domains.
Each site will have same layout.
Difference between each site would be the theme color , logo and the text shown to the user, which comes from different API for each site.
I can see this solution,
Request from all the domains will be routed to same controller, but to different actions.
@current_site = request.domain will hold the current domain.
Use domain constraints for each request to ensure , it goes to the right controller and action. (This becomes verbose , have to define each route 6 times for each domain )
Each action will render the same template.
Pass the @current_site name in a class attribute of the main div tag, which javascript can pickup to render the theme.

My questions are

  1. Is there any better method to achieve this especially the routing seems bulky?
  2. If the application scales to million users, @current_site variable would render the correct theme?
  3. Thread.current can be used to store the current_site information and read that wherever I want to ensure each thread gets correct @current_site info?

  1. This sounds like you're wanting to do a multi-tenant application basically. I did a couple episodes on this: https://gorails.com/episodes?utf8=%E2%9C%93&q%5Bname_or_description_or_notes_cont%5D=multiten

  2. I imagine that you can use @current_site to load and render the correct theme without having to separate it into multiple controllers and actions. They could point to the same one and it dynamically figures out which to render.

  3. You won't need Thread for this because each request that comes in will have the domain in the request so it will be able to detect which site to render. Most Rails apps aren't actually threaded but the webserver is, so you don't have to worry about it.


Thank you Chris as always for your valuable inputs.
Since the Rails app is an API Client, I do not have any tables in the database.
Can I use the Apartment Gem even in this case?


Probably not if you don't have a database. The gem is designed for that, but you could write a before_action that looks up the correct site as soon as the request starts. That would do basically the same thing as the Apartment gem. You'll just want something more custom in this case because what you're doing is a bit unique. The before_action should work great for this.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.