Multiple database handling with Rails
Posted by Sandro Paganotti in
Ruby on Rails -
comments are closed
What happen if your chief ask you to write an application that use more than one database? Wow… sound scaring, how to tell ActiveRecord that some models belong to a database and others to another? You’ll be surprised ‘cause it is quite easy.
Let’s start:
1. new database description:
Open your database.yml file. Under the three standard databases (development, test and production) add the informations needed to connect to you extra db. Use the standard yml sintax like:
extradb_development:
adapter: mysql
host: localhost
username: root
password: blabla
database: extradb_dev
extradb_test:
adapter: mysql
host: localhost
username: root
password: blabla
database: extradb_test
extradb_production:
adapter: mysql
host: localhost
username: root
password: blabla
database: extradb_prod
2. Create models
Create models using the command line tool as usual, just remember to delete the migration associated.
ruby script/generate model cat
ruby script/generate model dog
3. Associate models with extradb
You need to manually overwrite the estabilish_connection method for the models linked to the external database. Doing this in ‘application.rb’ using a ‘before_filter’ callback ensure that the connection will be always present. The code is quite simple:
class ApplicationController < ActionController::Base
require 'yaml'
before_filter :set_extra_db_connection
def set_extra_db_connection
extra_coord = YAML.load(File.open(File.join(RAILS_ROOT,"config/database.yml"),"r"))["extradb_"+ ENV['RAILS_ENV']]
Cat.establish_connection(extra_coord)
Dog.establish_connection(extra_coord)
end
end
4. Done!
Yess! You made it! Now you can use your ‘foreign models’ exactly like the normal ones. You can use validations and also relationship (also between model from different databases!).
Easy isn’t it?


Comments
planetmcd
Posted on December 11
Sandro Paganotti
Posted on December 12
Ghislain
Posted on December 13
Sandro Paganotti
Posted on December 13
Joe Martinez
Posted on December 19
Anthony Eden
Posted on January 06
Sandro
Posted on January 06