/ ?>>

Multiple Database connections in rails

By , July 29, 2011 2:20 pm

Here I am going to show how to connect  multiple database connection in rails.

Lets say there are 2 models

1. Company:  in db1

2. Website: in db2

First set connection parameters  for both database with different constant variables and define in environment file.


DB1 = {

:adapter => 'mysql',

:database => DATABASE1,

:username => USERNAME,

:password => PASSWORD,

:host => HOST

}

DB2 = {

:adapter => 'mysql',

:database => DATABASE2,

:username => USERNAME,

:password => PASSWORD,

:host => HOST

}

Add connection.rb file in lib folder


module Connection

  def self.included(base)

    base.class_eval do

    parameters = self::DB

    ActiveRecord::Base.establish_connection(

      :adapter  => parameters[:adapter],

      :host     => parameters[:host],

      :username => parameters[:username],

      :password => parameters[:password],

      :database => parameters[:database]

      )

   end
 end
end

include connection file and set DATABASE in models

in Company model

DB =  DB1
include Connection

in Website model


DB = DB2

include Connection

Now whenever Company model is used, it will establish connection for DB1 and for Website model it will establish connection DB2.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

3 Responses to “Multiple Database connections in rails”

  1. ravionrails says:

    You can also do it by defining database settings like we do for development,test,production in database.yml
    and use establish_connection(:name) in model

  2. Kalpit says:

    Hey Brijesh nice one, but how to specify connection in migration.

Leave a Reply

*

Panorama Theme by Themocracy