Using ActiveRecord on Multiple Databases

You can use ActiveRecord::Base#establish_connection, to connect to the desired database.

You could pass the db credentials to establish_connection as a Hash

establish_connection(
  adapter: 'mysql2',
  encoding: 'utf8',
  pool: 5,
  username: 'me',
  password: 'mypassword'
)

There are more examples here


I'm not sure you can do it in run time, since the database connection is coupled to the class (model)

However, you can make different classes to be connected to different databases I don't want to copy someone else answer, so just look at this post

Connecting Rails 3.1 with Multiple Databases

and give him the credit

Good luck