In some scenarios, we need data from an external database to execute in different applications. Here, we need a bridge that 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 databases, where the existing database and the external database will work simultaneously.
Let’s say there are two different rails applications say “myapp” and “remoteapp” where “myapp” depends upon “remoteapp” user table.
Step#1
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 connect_remote: 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: www.remoteapphost.com # host name of the db
Step#2
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 establish_connection("connect_remote") end
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.
Step#3
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 user’s 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 = User.new params[:user] user.save #update existing record user = User.find params[:id] user.update_attributes(params[:user])