Multiple Database connections in rails
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.

















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
Hi Ravi,
Thanks… its really easy ..
Thanks
Brijesh Shah
Hey Brijesh nice one, but how to specify connection in migration.