Serve Multiple Sites Or Views With A Single Rails Application

Posted by Weston Ganger on September 09, 2015

I had two blogs that I wanted to combine but main seperate views for each.

There are two main parts to it: Layout and View Paths

For layouts you create two seperate layout files in app/views/layouts

Ex. my_site.html.erb AND my_other_site.html.erb

Next you create the view folders for each site in app/views

Ex. my_site/ AND my_other_site/

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  layout :determine_site
  before_filter :determine_view_path


  def determine_site
    request.host == "mysite.com" ? "my_site" : "my_other_site"

  def determine_view_path
    prepend_view_path "#{Rails.root}/app/views/#{determine_site}"


Now it will determine which layout and which view folder to use based on the URL.


But what if you need to add Domain Specific routes to your app. First define a custom constraint:

class DomainConstraint
  def initialize(domain)
    @domains = [domain].flatten

  def matches?(request)
    @domains.include? request.domain

Then you can use it in your routes file:

# config/routes.rb

constraints DomainConstraint.new('mydomain.com') do
  root to: 'mydomain#index'

# or per route basis

root to: "main#my_action", constraints: DomainConstraint.new('mydomain.com')

root to: 'main#index' # root for all other sites

Related External Links:

Posted in Rails and Tagged with multisites rails 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts