Rails multiple databases

May 27, 2009 at 12:02 pm (Model) (, , , , )

Consider the case where some tables exist in database A and the others in B. Depending on the table under question, we have to connect to the specific Database and query it.

Supposing you have two databases say A,B.
Now you need configurations for both of them in database.yml (AS each RAILS configuration can point only one DATABASE)
let the development environment point database “A”
So create another environment called “dummy” point at database “B”

adapter  : mysql
username : user-name
password : password
database : A

adapter  : mysql
username : user-name
password : password
database : B

Consider two models:
a) Animal – table = animals in Database A.
b) Person – table – persons in Database B.

Usually the classes will be like follows:

class Person << ActiveRecord::Base

class Animal << ActiveRecord::Base

Now for Rails to know that it has to connect to DATABASE B when it needs to fetch data from Table “persons”, you hust have to add a line in the Person model. i.e:
establish_connection :dummy
establish_connection  Рmethod which connects to the Database specified in the environment
dummy – environment name

Thats it.
Try the following in console:

>> Animal.connected? #=> false
>> Animal
>> Animal.connected? #=> true

>> Person.connected? #=> false
>> Person
>> Person.connected? #=> true

connected? is the method which returns whether or not RAILS has connected with the DATABASE in which the table related to this MODEL exists.
Initailly when the RAILS application loads (CONSOLE starts), it has no DB connections.
When u say Animal, it fetches the schema of animals table by connecting to Database A.
So, after that , if u say Animal.connect? , it checks whether or not RAILS has connected to the DB in which the table related to Aniaml(animals) exists.
As it has already connected in the above step, the answer is TRUE.

Same is the case with Person.

The point to observe is that, Before working on the Model, Rails executes “establish_connection” method.
If it is not specified in the model, it connects to d DB as specified in the current ENVIRONMENT, if its not already connected.

But if we want o connect to a different DB as in the case with Person model, we override this, by specifying the DATABASE NAME to be connected by specifying the environment name in the “establish_connection” as the 1’st line of the Class.

Hope this is useful.

Permalink Leave a Comment