Skip navigation

This is a bit of a know how post. If your looking for a way to connect your Rails application to different databases, this will be of use. I am assuming that your application is clean enough for you to be able to associate specific models to specific databases. If this is not something that you can do, hang on till I complete my post Connecting to multiple databases on the fly.

class Task < ActiveRecord::Base

Notice the use of ActiveRecord::Base.configurations which returns to you all the configurations of environments in your database.yml file that will typically look like this.

  adapter: mysql
  database: rails_db1
  user: root
  password: root
  adapter: mysql
  database: rails_db2
  user: root
  password: root

ActiveRecord::Base.establish_connection is useful to connect to databases on the fly with a given set of configurations. So pick up the right config from the hash returned by the configurations class method and invoke the establish connection class method. Thats it.

All instances of Tasks created will now be bound to the tasks table of the rails_db2 i.e test configuration.

Note: This will not affect other models connectiong to the default Rails database as well. I have tested it for thread safety as well.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: