08.21.2019
Ruby on Rails connect multiple databases
For multiple database connection, you need to add the following codes to the database.yml file. Here, I am giving the example of connecting two databases from a rails application
To connect multiple databases from a rails application we need to config database.yml file like this.development:
adapter: mysql2
database: database1_dev
username: dbuser
password: dbpass
host: localhost
development_sec:
adapter: mysql2
database: database2_dev
username: dbuser
password: dbpass
host: localhost
production:
adapter: mysql2
database: database1_pro
username: dbuser
password: dbpass
host: localhost
production_sec:
adapter: mysql2
database: database2_pro
username: dbuser
password: dbpass
host: localhost
Here I have used two databases for the development and production environment.
Now we need to connect the model to databases. When you are running your application in development and production mode, all the models will be mapped through the development and production database parameters that had been mentioned in your database.yml. So for some model we need to connect to other database.
Lets assume that, we have two models User and Article. The users table is in database1_dev and database1_pro, the articles table in database2_dev and database2_pro.
Article model
class Article < ActiveRecord::Base
establish_connection "#{Rails.env}_sec"
end
Similarly, when you adding the new migration for the second database, need to
add following code to it.
class CreateArticles < ActiveRecord::Migration
def connection
ActiveRecord::Base.establish_connection("#{Rails.env}_sec").connection
end
def change
# your code goes here.
end
end