Pelle
Pelle

Reputation: 6578

Switch Rails database connection on the fly

I have a dev database in my Rails 5 app, but in our network, we also keep a populated database to test stuff on. Sometimes, I have to switch between these databases all the time, and I would save a lot of time if I could do that immediately while Rails is running.

I've tried removing all active connections, and then patching the configuration, but somehow it keeps connecting to my original database.

This is what I tried:

Product.count
  => 0 # is dev db

ActiveRecord::Base.connection_handler.remove_connection('development')
ActiveRecord::Base.connection_handler.remove_connection('primary')
ActiveRecord::Base.configurations['development'] = test_config_params

Product.count

=> 0 # Is still dev db

Where does Rails cache this old connection information, and how can I remove / replace it?

Upvotes: 2

Views: 3512

Answers (1)

R. Sierra
R. Sierra

Reputation: 1204

You can change database connections by using ActiveRecord::Base.establish_connection(config). In case ActiveRecord::Base.configurations is set (Rails automatically loads the contents of config/database.yml into it), a symbol can be given as argument, representing a key in the configuration hash like :development or :test

Check the complete docs here

Upvotes: 5

Related Questions