Last active
March 7, 2022 01:23
-
-
Save fernandoalmeida/1894615 to your computer and use it in GitHub Desktop.
Rails multi-tenant / multi-database with subdomains using database.yml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
after "deploy:migrate", "deploy:migrate_subdomains" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, you will not get exeption after establish_connection. This is bettter solution: