Tuesday, February 2, 2010

Multiple Databases for Rails

I had to write a solution for a legacy database to join a current database. In essence I had 3 databases to work with, and needed the app to move between them easily and without errors. After much research and endless solutions that didn't work I finally configured this solution to work consistently.

In the config/database.yml add the relevant database:

newdb:
adapter: mysql
encoding: utf8
reconnect: false
database: thedatabasename
pool: 10
username: myuser
password: mypass
host: hostaddress
port: 3306
socket: /var/run/mysqld/mysqld.

In the model(not the controller) add the following to EVERY model and controller that connects to that database:

establish_connection :newdb

Then you can add the other set items you require to the model (not the controller):

set_table_name "thetablename" ##if you want a singular table name and not plural
set_primary_key "theprimkey" ##if the primary key like in legacy databases is not id or something

Now, the trick to making this work with several databases is that in all the models that connect to the development database you add:

establish_connection :development ##or production

You get "cant find the database" and other errors if you move from controller/page to controller/page without this in each controller. Its actually the biggest key to the puzzle.

If you follow this simple procedure you should succeed.

No comments:

Post a Comment