Sometimes when using Active Record you may want to create a database connection to a database other than the default database specified in your database.yml file.
When this happens, the easiest way to do it is to use the Class-level convenience method on ActiveRecord::Base. Like this:
Imagine your database.yml entry looks like this:
development_foo: adapter: mysql encoding: utf8 database: foo pool: 5 username: my_user password: my_pass socket: /tmp/mysql.sock
Now you want to create active record models that use that database connection. Here’s how:
# 'Bar' model points to the table 'bars' in the database 'foo' class Bar < ActiveRecord::Base # specify the database.yml entry $db_config = 'development_foo' # Fetch the database.yml configuration $config = ActiveRecord::Base.configurations[$db_config] # Now we can establish a connection to that database and # this ActiveRecord model class will point to that database. establish_connection $config end
It’s simple!