whatsapp_btn
whatsapp_btn Chat With Us

Home >> RoR >> How to Set Up Ruby on Rails Multiple Databases with Active Record?

How to Set Up Ruby on Rails Multiple Databases with Active Record?

  5 min read
How to Set Up Ruby on Rails Multiple Databases with Active Record_

As your Rails application grows and becomes more well-known, its strain on your database may become a bottleneck. The growing amount of data and traffic significantly impacts the application’s performance. Using multiple databases is one way to address this issue.

Ruby on Rails Version 6 introduces the ability to distribute data over many databases, which can significantly improve the speed and responsiveness of your application.

You can optimise your database’s structure for optimal performance in a Ruby vs Ruby on Rails comparison by handling read and write operations separately or partitioning the different data types. This leads to decreased load times, enhanced user experience, and increased application scalability overall.

Let’s start by setting up and using multiple databases in your Rails application. This course will examine the configuration process and discuss the benefits of using Ruby on Rails with different databases.

What is Multiple Databases in Ruby on Rails?

Multiple databases can be connected to and interacted with simultaneously by a Ruby on Rails application. This feature is known as many databases for Ruby on Rails. They were initially included in Ruby on Rails version 6 to help developers manage databases successfully. By effectively integrating multiple databases, developers using Rails can potentially improve their applications’ performance, scalability, and maintainability.

It also lessens the amount of data load that large-scale applications have to handle and helps them handle data with low requirements. It allows you to separate the writing and reading processes, which yields incredibly good performance. It can store different data types in various databases for organizational and security purposes.

These are its main attributes:

  • This configuration defines the various database connections found in the database.yml file.
  • Utilize model association to obtain models for specific databases.
  • Schema changes for each database must be managed independently during a migration, if feasible.
  • Reading/writing splitting automates reading and writing operations to particular databases and routing.

Advantages and Disadvantages of Ruby on Rails Multiple Databases

Advantages and Disadvantages of Ruby on Rails Multiple Databases

Advantages:

Ruby on Rails provides many advantages. Its quick development can be attributed to two factors: it offers many libraries and places conventions above configurations. RoR prioritizes code simplicity, leading to more straightforward, easier-to-maintain programs. It also benefits from having a solid community, copious documentation, and a wide range of open-source gems that enhance its usefulness.

  • Time savings:

Although the principles of this structure are relatively easy to understand, it will take some time for you to see the full potential of this framework. However, if you are prepared to invest a small amount of time in your project, you will surely be amazed at how advanced you have advanced.

There are also hundreds of tools available that can help you save time on simple tasks that take a lot of effort to complete and speed up and simplify your entire coding experience.

In other words, this suggests you can do more simultaneously. This is why many offline and online universities offer Ruby on Rails-specific classes. Additionally, this suggests that the community is expanding, which indicates that future apps will be even more valuable and productive. Salutations!

  • Helpful tools and libraries available:

A vast array of valuable “gems” and”libraries created by the community can be integrated into your applications. These libraries and jewels number in the hundreds. However, you can also find even more helpful tools incorporated inside them. Their impact touches on all aspects of your experience with software design, not just the content of your code.

Some will help you with debugging, some will be very helpful with optimization, and some will relate to the testing part of your work.

  • A large and active community:

A large community of people is creating RoR on GitHub. Besides this, there are many different software programs, each with specialized uses. These little pieces of information, more widely called “gems,” can be used as a starting point for your project, freeing you up to focus on more challenging tasks. Furthermore, this suggests that you always ask for help if needed while you’re starting.

  • Adherence to the guidelines:

One advantage of RoR is that it offers strong support for web standards for all application areas, including data transport and user interface. Applications produced using Ruby on Rails are anticipated to follow accepted software design concepts. 

Disadvantages:

As with any other programming language or framework, RoR undoubtedly has certain disadvantages during development. There are, however, a few possible issues that you might run into.

  • A lack of flexibility

Regarding core responsibilities and functions, RoR is almost entirely superior. But, because so many premade items are already prepared, there are few opportunities for creativity. Before deciding which framework to use for a particular project, you should consider the framework’s elements and ascertain whether one is more traditional or unique.

  • Evolution is a continuous process:

It’s important to know where to put this specific problem about the benefits and drawbacks of Ruby on Rails and the Ruby language. It is undoubtedly a good thing and a natural process when something improves, especially for a language with such a vast and vocal populace. But it can be challenging to get used to, especially for individuals who are just starting and are unfamiliar with the circumstances.

Moreover, most changes are not limited to the framework itself; they also affect the community-built tools and libraries. They consistently create new features, enhancements, and additions. Integrating with the community would help guarantee that you are always informed about everything.

How do you set up multiple Ruby on Rails databases?

We currently have four databases set up here: primary, primary_replica, primary2_replica, and primary2. They all have distinct configurations, including migration routes.


default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: your_username
  password: your_password
  host: localhost

development:
  primary:
    <<: *default
    database: multidb_development
    migrations_paths: 
      - db/primary_migrate

  primary_replica:
    <<: *default
    database: multidb_development
    replica: true

  secondary:
    <<: *default
    database: multidb_development2
    migrations_paths: 
      - db/secondary_migrate

  secondary_replica:
    <<: *default
    database: multidb_development2
    replica: true

Nevertheless, there are a few key points that you should remember while interacting with several databases:

1. The names of the databases must be the same for both the primary database and its replica at the same time since they both hold the same data. This is equally true concerning the second database.

2. Verify that each username in the primary database and its replica is distinct. The replica user should only be able to read; writing is inappropriate.

3. You will need to include a "replica: true" lin" in the database.yml file about the replica if you are using a replica database. This is necessary since Rails does not automatically distinguish between a writer and replica databases. Certain operations, like migrations, cannot be performed by Rails on replicas.

When working with databases other than the primary writer database, make sure the migrations_paths variable is set to the location where you want to store migrations for that database.

Creating Models for Each Database

To create a structure that separates models based on different databases, you can create custom base classes (PrimaryRecord and Primary2Record) for each database. These base classes will handle the connection to the appropriate database, making the models more modular and maintainable.

Here’s how you can proceed:

Step 1: Generate the Models for Different Databases

Run the following commands to generate the models tied to specific databases:


1. Generate Post model for the primary database:

rails generate model Post title:string body:text --database=primary

2. Generate User model for the primary2 database:
bash
Copy code
rails generate model User name:string email:string --database=primary2


This will create the model files under the app/models directory as usual.

Step 2: Create Custom Base Classes for Each Database

Next, you’ll create PrimaryRecord and Primary2Record classes that will act as the base for models in the primary and primary2 databases respectively.


1. Create primary_record.rb under app/models:

# app/models/primary_record.rb
class PrimaryRecord < ApplicationRecord
  self.abstract_class = true

  # Connects to the primary database
  connects_to database: { writing: :primary, reading: :primary_replica }
end


2. Create primary2_record.rb under app/models:

# app/models/primary2_record.rb
class Primary2Record < ApplicationRecord
  self.abstract_class = true

  # Connects to the primary2 database
  connects_to database: { writing: :primary2, reading: :primary2_replica }
end


These abstract classes will ensure that any model inheriting from them will automatically connect to the right database. By default, Rails expects the database roles to be writing and reading for the primary and replica respectively. If you have a legacy system you may already have roles set up that you want to keep the same. In that case, you can set a new role name in your application config.


config.active_record.writing_role = :default
config.active_record.reading_role = :readonly


Step 3: Update the Models to Inherit from the Custom Base Classes

Now that you have the custom base classes, update the models to inherit from them instead of ApplicationRecord.


1. For Post model, which uses the primary database:

# app/models/post.rb
class Post < PrimaryRecord
  # Post-specific logic here
end

2. For User model, which uses the primary2 database:

# app/models/user.rb
class User < Primary2Record
  # User-specific logic here
end

By inheriting from PrimaryRecord or Primary2Record, these models will be scoped to their respective databases.

Step 4: Ensure Proper Database Configuration

Make sure your config/database.yml is correctly set up to handle the primary and primary2 databases. Here’s an example:


default: &default
  adapter: postgresql
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  primary:
    <<: *default
    database: primary_db
    username: primary_user
    password: password123
  primary_replica:
    <<: *default
    database: primary_db
    username: primary_user
    password: password123
    replica: true
  primary2:
    <<: *default
    database: primary2_db
    username: primary2_user
    password: password456
  primary2_replica:
    <<: *default
    database: primary2_db
    username: primary2_user
    password: password456
    replica: true

Step 5: Running Migrations

Run migrations for each database separately:


Migrate for the primary database:

rails db:migrate:primary

Migrate for the primary2 database:

rails db:migrate:primary2


Summary

  • You’ve generated the models Post and User with connections to different databases.
  • You created abstract classes PrimaryRecord and Primary2Record to manage connections for models related to their respective databases.
  • The models now inherit from these custom base classes, ensuring proper database connections.
  • Make sure your migrations and database configurations are set up to reflect this multi-database structure.

How to Set Multiple Databases with Replicas

Once you have configured multiple databases in Ruby on Rails, you can use an additional method in your Rails application to use different models. In addition to the primary database configuration, it is standard practice to include database clones for redundancy and load dispersion.

Replicas are copies of the primary database restricted to read access; they can be used to improve fault tolerance and performance. Let me take you through the steps in configuring replicas for our Rails 6 application.

Why Is It Beneficial to Use Replicas?

Replicas are used for many different things in Ruby on Rails 7.2, such as the following:

1. Reading scaling, which divides read operations among several copies, will increase your application's performance.

2. Redundancy provided by replicas guarantees that, even in the case of a primary database failure, you can still send read requests from the replicas.

3. By distributing the read load equally among your many replicas, you can avoid overburdening any one replica.

Conclusion

Following these steps, you can build a Rails 6 application that communicates with several databases and models. To effectively manage your project, consider hiring Ruby on Rails developers who specialize in this framework. This approach is an excellent option for handling the many data requirements connected with complex projects because it is scalable and versatile. It is advised to experiment with different setups to fully take advantage of Rails's ability to manage many databases efficiently.

FAQ'S:

One of the most frequent complaints about RoR is its "slow" run" time performance, which makes expanding your RoR applications more challenging. While some of the best environments and frameworks—like Node.js or Django—are a little bit faster than RoR, performance issues with your application are highly improbable. This is due to the fact that the user base of your application is not as huge as that of really popular websites like Twitter.


Tagline Infotech
Tagline Infotech a well-known provider of IT services, is deeply committed to assisting other IT professionals in all facets of the industry. We continuously provide comprehensive and high-quality content and products that give customers a strategic edge and assist them in improving, expanding, and taking their business to new heights by using the power of technology. You may also find us on LinkedIn, Instagram, Facebook and Twitter.

Related Posts :

contact-us-bg

Our Global Presence

India

Surat (HQ)

Digital Valley, 423, Apple Square, beside Lajamni Chowk, Mota Varachha, Surat, Gujarat 394101

Ahmedabad

D-401, titanium city center, 100 feet anand nagar road, Ahmedabad-380015

 +91 9913 808 285

U.S.A

1133 Sampley Ln Leander, Texas, 78641

United Kingdom

52 Godalming Avenue, wallington, London - SM6 8NW

U.A.E

Office No - 43-44, Al Fahidi, Bur Dubai, Dubai, United Arab Emirates

 +971 58 569 4786