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

5 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.

  3. cars says:

    The process of buying a car can be extremely taxing.
    Some people might not know a lot about cars, but there are others who know too much and constantly feel like they aren’t getting a good deal. You can get the best car at the best price by following this advice.

  4. Bridget says:

    Hi there, I discovered your blog by means of Google even as looking for a similar matter, youyr web site got here up, it seems good.

    I’ve bookmarked it in my google bookmarks.
    Hi there, simply become aware of your blog thru Google, and located that it’s truly informative.
    I’m gonna be careful for brussels. I’ll be grateful when yyou continue this in future.
    Lots of other folks will likely be benefited out of your writing.
    Cheers!

Leave a Reply

*

Panorama Theme by Themocracy