How can I dynamically change the Active Record database for all models in Ruby on Rails?

21,960

Solution 1

You can also do this easily without hardcoding anything and run migrations automatically:

customer = CustomerModel.find(id)
spec = CustomerModel.configurations[RAILS_ENV]
new_spec = spec.clone
new_spec["database"] = customer.database_name
ActiveRecord::Base.establish_connection(new_spec)
ActiveRecord::Migrator.migrate("db/migrate_data/", nil)

I find it useful to re-establish the old connection on a particular model afterwards:

CustomerModel.establish_connection(spec)

Solution 2

you can change the connection to ActiveRecord at any time by calling ActiveRecord::Base.establish_connection(...)

IE:

 ActiveRecord::Base.establish_connection({:adapter => "mysql", :database => new_name, :host => "olddev",
    :username => "root", :password => "password" })

Solution 3

It's been a while since this question has been created, but I have to say that there is another way too:

conn_config = ActiveRecord::Base.connection_config
conn_config[:database] = new_database
ActiveRecord::Base.establish_connection conn_config

Solution 4

class Database
  def self.development!
    ActiveRecord::Base.establish_connection(:development)
  end

  def self.production!
    ActiveRecord::Base.establish_connection(ENV['PRODUCTION_DATABASE'])
  end

  def self.staging!
    ActiveRecord::Base.establish_connection(ENV['STAGING_DATABASE'])
  end
end

And in .env (with dotenv-rails gem for instance):

PRODUCTION_DATABASE=postgres://...
STAGING_DATABASE=postgres://...

And now you can:

Database.development!
User.count
Database.production!
User.count
Database.staging!
User.count
# etc.
Share:
21,960
Tilendor
Author by

Tilendor

I'm a programmer & Geek

Updated on October 29, 2020

Comments

  • Tilendor
    Tilendor over 3 years

    In our program, each customer gets their own database. We e-mail them a link that connects them to their database. The link contains a GUID that lets the program know which database to connect to.

    How do I dynamically and programatically connect ActiveRecord to the right db?