Wednesday, October 15, 2008

Multiple Database Connections using ActiveRecord

Define your extra database connections In the database.yml config file:

development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000

db1:
adapter: sqlite3
database: db/db1.sqlite3
timeout: 5000

db2:
adapter: sqlite3
database: db/db2.sqlite3
timeout: 5000

Now create a dbx.rb file in your models directory and define a class for each database connection:

class Db1 < ActiveRecord::Base
self.abstract_class = true
establish_connection "db1"
end

class Db2 < ActiveRecord::Base
self.abstract_class = true
establish_connection "db2"
end

Add the following to your environment.rb file:

include "dbx"

You will now be able to use "Db1" and "Db2" in your app to connect to 2 other databases.

Open up an existing model class in your project:

class User < ActiveRecord::Base
has_many :messages, :dependent => :destroy
end

Now replace "ActiveRecord::Base" with "Db1"

class User < Db1
has_many :messages, :dependent => :destroy
end

The User class is now set to retrieve data from the "db1" database.

1 comment:

James Fleeting said...

Nice, really easy to add/use multiple databases with Rails. Looking forward to more posts. :)