Quick Summary:

As applications become complex, managing data across multiple databases becomes increasingly essential. Rails 6 introduced robust support for this scenario, making creating applications that interact with multiple databases and models to handle sophisticated data structures easier. This blog on Ruby on Rails multiple databases will cover everything you need to know to set up a massive database seamlessly.

Table of Contents

Introduction:

As your Rails application grows and gains popularity, the strain on your database can become a bottleneck. In fact, the increase in traffic and data volume significantly impacts app performance. That’s where multiple databases come in.

Introduced in Ruby on Rails Version 6, this feature allows you to distribute data across several databases, significantly boosting your app’s speed and responsiveness.

By separating different data types or handling read and write operations independently, you can optimize your database structure for maximum efficiency. This results in faster load times, enhanced user experience, and overall scalable application.

Let’s dive into how to set up and utilize multi databases in your Rails app. We will explore the configuration process and discuss the benefits of Ruby on Rails multiple databases.

What is Multiple Databases in Ruby on Rails?

Ruby on Rails multiple databases indicate the ability of a Rails application to interact with and connect with more than one database simultaneously. They were introduced in Ruby on Rails 6 and help developers manage databases effectively. By effectively implementing multiple databases, Rails developers can improve application performance, scalability, and maintainability.

Moreover, it assists large-scale applications in handling data with minimum requirements and reducing the data load. In addition, it allows you to separate read and write operations for excellent performance. It also can store different types of data in separate databases for safety and organizational purposes.

Its primary features are:

  • Configuration: It defines multiple database connections in the database.yml file.
  • Model Association: Develop models for specific databases.
  • Migrations: Manage schema changes for each database independently.
  • Read/Write Splitting: Automate routing and read and write operations for particular databases.

Advantages and Disadvantages of Ruby on Rails Multiple Databases

Through advantages and disadvantages, let’s understand the significance of multiple databases in Ruby on Rails.

Advantages:

1. Scalability: Multiple databases allow you to scale different application parts independently, improving performance under heavy loads.

2. Data Segregation: You can segregate sensitive or high-traffic data into separate databases, enhancing security and management.

3. Flexibility: Using multiple databases allows choosing appropriate database technologies for different data types.

4. High Availability: It provides redundancy, ensuring high availability and fault tolerance in case of primary database failures.

5. Performance: Distributing read operations across replicas can significantly improve the overall performance of your application.

Disadvantages:

1. Complexity: Managing multiple databases adds complexity to your application architecture, requiring careful planning and maintenance.

2. Synchronization: Keeping data synchronized across multiple databases can be challenging and may require additional tooling or processes.

3. Cost: Using multiple databases may incur higher infrastructure costs, especially when deploying replicas for high availability.

4. Consistency: Ensuring data consistency across multiple databases, especially during write operations, can be complex and may require implementing distributed transaction management.

How to Set Up Ruby on Rails Multiple Databases?

First and foremost, you need to set up your applications. Moreover, you can use the below-mentioned version of Ruby and Rails:

Ruby — 2.7.2
Rails — 6.1.7

Let’s configure our Rails application to connect to multiple databases. In the config/database.yml file, define connections for each database:

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

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

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

  primary2:
    <<: *default
    database: multidb_development2
    migrations_paths: db/primary2_migrate

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

Here, we have set up four databases: primary, primary_replica, primary2, and primary2_replica. Each has its own configuration, including migration paths.

However, while using multiple databases, there are some crucial points that you must remember:

1. Make sure that the names of the databases are the same for both the primary and its replica because they contain the same data. This applies to the second database as well.

2. Use different usernames for the primary database and its replica. The replica user should only have permission to read, not write.

3. If you’re using a replica database, you’ll need to add a “replica: true” entry to the replica in the database.yml file. This is necessary because Rails doesn’t automatically distinguish between a replica and a writer database. Rails won’t perform certain tasks, like migrations, on replicas.

4. For databases other than the primary writer database, you’ll need to set the migrations_paths to the directory where you’ll store migrations for that database.

Want to enhance your database performance and streamline data integration?

Hire Ruby on Rails developers to craft efficient, scalable solutions tailored to your needs. Connect with us to transform your database management.

Creating Models for Each Database

Now, let’s generate models for each database. We’ll also create an abstract class to handle connections for one of the models. Run the following commands:

Copy Text
rails generate model Post --database=primary
rails generate model User --database=primary2

This will create model files under the app/models directory for each database. Additionally, create a files primary_record.rb and primary2_record.rb under app/models with the following content:

Copy Text
# primary_record.rb
class PrimaryRecord < ApplicationRecord
  # `connects_to` can only be called on ActiveRecord::Base or abstract classes
  self.abstract_class = true

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

# primary2_record.rb
class Primary2Record < ApplicationRecord
  # `connects_to` can only be called on ActiveRecord::Base or     abstract classes
  self.abstract_class = true

  # Connects our application directly to the database
  connects_to database: { writing: :primary2, reading: :primary2_replica }
end
Copy Text
# post.rb
class Post < PrimaryRecord
   # Add logic code here
end

# user.rb
class User < Primary2Record
   # Add logic code here
end

We made this change because if we directly use connects_to inside the User class, accessing the User model will result in an error message like:

“connects_to method can only be called on ActiveRecord::Base or abstract classes.”

To address this issue, we created the Primary2Record class and inherited it into the User class.

Note: After running rails db:migrate, the users table will be created inside the ‘multidb_development2’ database, and the posts table will be created inside the ‘multidb_development’ database.

Running Migrations

When running migrations, specify the database using the –database option:

Copy Text
# The following command will create a migration file for the users table inside the db/primary2_migrate directory because we specified the database while running the migration command.
rails g migration CreateUsers email --database=primary2

# This command should run specific migrations located in the db/primary2_migrate directory.
rails db:migrate:primary2

# This command should run all migrations for all databases.
rails db:migrate

# The following command will create a migration file for the posts table inside the db/primary_migrate directory because we specified the database while running the migration command.
rails g migration CreatePosts title --database=primary

How to Set Multiple Databases with Replicas

After setting up Ruby on Rails multiple databases, you can avail another method for using various models in your Rails application. In addition to configuring primary databases, it’s common to have database replicas for redundancy and load distribution.

Replicas are read-only copies of the primary database, allowing for improved performance and fault tolerance. Let’s explore how to set up replicas in our Rails 6 application.

We have configured two additional databases with replicas: primary_replica and primary_replica2. Let’s dive into what each section means:

➤ primary_replica: This configuration specifies a replica database named multidb_development_replica. The replica: The line indicates that this database replicates the primary database. Replicas are typically used for read operations to offload traffic from the primary database and improve overall performance.

➤ primary_replica2: Similarly, this configuration defines another replica database named multidb_development_replica2. Again, replica: true denotes that this database replicates the primary database primary2.

Why Use Replicas?

Replicas serve several purposes using in Ruby on Rails 7.2, such as

1. Read Scaling: Distributing read operations across replicas can improve your application’s overall read performance.

2. High Availability: Replicas provide redundancy, ensuring that you can continue serving read requests from the replicas if the primary database fails.

3. Load Balancing: With multiple replicas, you can balance the read load across them, preventing any single replica from becoming overwhelmed.

Conclusion

With these steps, you can build a Rails 6 application that interacts with multiple databases and models. This approach offers flexibility and scalability, making it suitable for handling diverse data requirements in complex projects. Experiment with different configurations to leverage Rails’ full potential in managing multiple databases seamlessly.

If you want expert guidance and development support for Ruby on Rails multiple databases, partner with a Ruby on Rails development company. Our professionals will help you optimize your Rails apps and ensure efficient data management, providing superior project performance.

Want an Expert Take on Rails Multiple Database?

Get in touch with our skilled professionals for scalable and dynamic solutions. Let us help you achieve seamless data management and unmatched efficiency.

Get Rails Consultation

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?