/ RAILS

Rails 6 ActiveRecord supports Multi DB connection switching

Rails 6 ActiveRecord supports Multiple database connection switching. Moreover, we can use different database connections for reading / writing with use of replicas to improve performance of the application.

Before Rails 6, developers preferred gems like SecondBase or MultiVerse to be able to connect models to different databases. They had their own pros and cons, thus some also implemented their own methods to be able to connect to multiple databases in Rails.

Rails 6 removes this dependency over gems to connect to different DBs. This change added two APIs for ActiveRecord.

1. Multi DB support for reading / writing

New method connects_to is added to be able to connect to multiple database for reading / writing

connects_to database: { reading: :read_replica_db, writing: :write_replica_db }

What this means is

  • ActiveRecord will use read_replica_db connection configuration specified in database.yml to perform read queries on the model.
  • ActiveRecord will use write_replica_db connection configuration specified in database.yml to perform write queries on the model.

This can be used in models created in a Rails application.

Let’s say, we have a model with name Product as given below.

class Product < ApplicationRecord
  self.abstract_class = true
  connects_to database: { writing: :products_primary, reading: :products_read }
end
  • This configuration will use products_primary database to perform write queries on products table
  • This configuration will use products_read database to perform read queries on products table

2. Switch roles or database connections

A block method connected_to is added to support switching of database connections. This is specifically useful if we want to retrieve certain data from another database or if we want to connect to read replica to perform some heavy querying etc.

connected_to by role

This block method can be used as given below.

ActiveRecord::Base.connected_to(role: :reading) do
  Product.first # finds product from replica connected to ApplicationRecord
end

It will create a database connection with :reading role.

connected_to by role

This block method can be used as given below.

ActiveRecord::Base.connected_to(database: :slow_replica) do
  Product.first
end

This will use database configuration specified in database.yml with name slow_replica and perform the query given in the block with ActiveRecord.

References:

akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee