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.

Linux copy facility

Sometimes I see guys struggling with copying in Linux. I thought I would add the options I use to help.

To copy a file use:

cp oldfilename newfilename

To rename a file you can use:

mv oldfilename newfilename

To copy a folder use:

cp -r oldfoldername newfoldername

There are other options, use cp --help to find out what they are.

To remove a file you use:

rm filename

to remove a folder:

rm -r foldername

The remote server copy of folder to folder can be done via an scp or rsync command:

scp -r foldername username@destinationiporaddress:/home/username

The home/username can be changed to suite, but its preferably a writeable directory.

Hope this helps someone