cktxqq
Last Updated: January 21, 2017
·
205
· Ganesh071190

Managing multiple database in rails

We can manage multiple database in rails in the following ways

Create your all database entry in database yml (Enviroment vise) Like below
development:
adapter: sqlserver
dsn: VANexusConn
#mode: odbc
database: database
name
username: databaseusername
password: database
password
host: 172.16.1.11
timeout: 10000

fixeddb:
adapter: sqlserver
dsn: VANexusConn
#mode: odbc
database: database
name
username: databaseusername
password: database
password
host: 172.16.1.11
timeout: 10000

indexeddb:
adapter: sqlserver
dsn: VANexusConn
#mode: odbc
database: database
name
username: databaseusername
password: database
password
host: 172.16.1.11
timeout: 10000

Now using active record "establishconnection(:connectionnameofyml_file)" method you can use database in any model.

Using connection for multiple models:

Create a "Abstract Class" and Inherit these class in model In which you want to access these connection for example:
class IndexedDb < ActiveRecord::Base
#Abstruct class no methods here, class which inherite these class will take care ot them
self.abstract_class = true

#Establish connection to indexdb
establish_connection(:indexeddb)
end

Now use these class in model like this
Bonus < IndexedDb
end
Now bonus model use" indexeddb" database

Second way:
Define database yml like these
efaults: &defaults
username: root
password: 1234567
adapter: mysql2
encoding: utf8
collation: utf8unicodeci

db1:
development:
database: db1_development
host: localhost
<<: *defaults

test:
database: db1_test
host: localhost
<<: *defaults

staging:
database: db1_staging
host: localhost
<<: *defaults

production:
database: db1_production
host: localhost
<<: *defaults

db2:
development:
database: db2_development
host: localhost
<<: *defaults

test:
database: db2_test
host: localhost
<<: *defaults

staging:
database: db2_staging
host: localhost
<<: *defaults

production:
database: db2_production
host: localhost
<<: *defaults

I configure two separate databases db1 & db2.
ENV['ENV'] ||= 'development'

dbconf = YAML::load(File.open(File.join(APPPATH,'config','database.yml')))

DB1CONF = dbconf["db1"][ENV['ENV']]
DB2CONF = dbconf["db2"][ENV['ENV']]

Connecting Models
class User < ActiveRecord::Base
establishconnection DB1CONF
end
Now user model use DB1_CONF database

Say Thanks
Respond