Skip to content

Instantly share code, notes, and snippets.

@sanbiv
Created October 15, 2015 08:46
Show Gist options
  • Save sanbiv/cf7c5f47b130697c5ae7 to your computer and use it in GitHub Desktop.
Save sanbiv/cf7c5f47b130697c5ae7 to your computer and use it in GitHub Desktop.
Rails multi-tenant / multi-database with subdomains using database.yml
before_filter :select_database
def select_database
if Rails.env == "production"
unless request.subdomain.empty?
begin
subdomain = request.subdomains.first
config = ActiveRecord::Base.configurations[subdomain]
if config
ActiveRecord::Base.establish_connection(config)
else
ActiveRecord::Base.establish_connection(Rails.env)
flash[:error] = "Database not found"
end
rescue
render :text => "Invalid subdomain"
end
end
end
end
common: &common
adapter: postgresql
username: username
password: password
host: localhost
encode: utf8
# Subdomains
subdomains: ["sub1", "sub2", "sub3"]
sub1:
<<: *common
database: sub1
sub2:
<<: *common
database: sub2
sub3:
<<: *common
database: sub3
task :migrate_subdomains do
configs = YAML::load(File.open(File.expand_path("../../../config/database.yml", __FILE__)))
configs["subdomains"].each do |subdomain|
begin
run "cd #{current_path} && #{rake} db:migrate RAILS_ENV=#{subdomain}"
rescue Exception => e
Capistrano::CLI.ui.say "*** [err] #{e.message}"
end
end
end
after "deploy:migrate", "deploy:migrate_subdomains"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment