How to implement “Multiple Database(DB) Connection” in Rails3

How to implement “Multiple Database(DB) Connection” in Rails3

2 Minutes Read

Rails1(1)In some scenarios we need data from a external database to execute in different application. Here, we need a bridge which will connect these two different databases. In Ruby on Rails this can be achieved through ActiveRecord’s establish_connection(). Following are the steps to create a rails application which uses multiple database, where the existing database and the external database will work simultaneously.
Let’s say there are two different rails application say “myapp” and “remoteapp” where “myapp” depends upon “remoteapp” user table.


Edit the ‘database.yml‘ file for the ‘myapp‘ project
Add a new connection for ‘remoteapp‘ as below:

# Connection name, it will be used to connect from myapp
adapter: mysql2
username: user_name             # username of the remoteapp database
password: password             # password of the remoteapp database
pool: 5
database: remoteapp_db_name    # database name of the remoteapp
host:      # host name of the db


In models folder create a new file called user.rb if it is not already there. Write below code to establish connection with remote app’s database.

class User < ActiveRecord::Base

Here use the connection name defined in the database.yml file in the establish_connection() method.
Like this you can create models to connect with remote databases.

It will give you the flexibility for managing users data of remote app’s database like it is present in the myapp  database.
Use the normal way to get data from the users table like

User.all                   #To get all the records
User.find(id)              #To get required record

Here you can also insert or update data in users table by normal way as it is
present in myapp application

#insert new record
user = params[:user]
#update existing record
user = User.find params[:id]
Jayadev Das

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘bout Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

No Comments

Post A Comment

Exit pop up

Before You Go...!

Subscribe to Andolasoft Blog

Stay up to date with the latest techniques of web & mobile app development service tips and our SaaS and open source product news.
Holler Box