Skip to content

Instantly share code, notes, and snippets.

@fernandoalmeida
Last active March 7, 2022 01:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fernandoalmeida/1894615 to your computer and use it in GitHub Desktop.
Save fernandoalmeida/1894615 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"
@boblin
Copy link

boblin commented Mar 20, 2012

Hi, you will not get exeption after establish_connection. This is bettter solution:

    ActiveRecord::Base.establish_connection(
      :adapter  => ActiveRecord::Base.configurations[Rails.env]['adapter'],
      :host     => ActiveRecord::Base.configurations[Rails.env]['host'],
      :username => ActiveRecord::Base.configurations[Rails.env]['username'],
      :password => ActiveRecord::Base.configurations[Rails.env]['password'],
      :database => subdomain
    )

    begin
      ActiveRecord::Base.connection.active?
    rescue
      render :text => "Invalid Subdomain"
      ActiveRecord::Base.establish_connection(Rails.env)
    end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment