Connecting Multiple Databases in Rails 5
Tags: rails, ruby, database, programming
Published: 2023-08-29 12:54:35

Ruby on Rails is a powerful web framework that makes building web applications a breeze. In some scenarios, you might find yourself needing to work with multiple databases within a single Rails application. This could be due to various reasons, such as managing different types of data or segregating data for performance optimisation. In this article, we'll explore how to connect and interact with multiple databases in a Rails 5 application.

## Setting Up the Databases

Before we dive into the code snippets, let's set up the scenario. Imagine you have a Rails application that needs to interact with two separate databases: a primary database for user data and a secondary database for product information. Here's how you can configure your database.yml file to define the connection settings for both databases:

```
# config/database.yml

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

development:
  <<: *default
  database: primary_db_development

secondary_development:
  <<: *default
  database: secondary_db_development
```

In the above configuration, we have defined two separate sections: development for the primary database and secondary_development for the secondary database. Make sure to replace your_username and your_password with the appropriate credentials.

## Defining Database Models

Next, we need to create models for each of the databases. Let's create two models: User for the primary database and Product for the secondary database.

```
# app/models/user.rb

class User < ApplicationRecord
  establish_connection :development # Connect to the primary database
end
```

```
# app/models/product.rb

class Product < ApplicationRecord
  establish_connection :secondary_development # Connect to the secondary database
end
```

In the above code, we use the establish_connection method to specify which database connection to use for each model. This way, the User model will use the primary database connection, and the Product model will use the secondary database connection.

## Performing Database Operations

Now that we have our models set up, let's see how to perform basic database operations on each database.

## Primary Database Operations

```
# Create a new user in the primary database
user = User.create(name: 'John Doe', email: 'john@example.com')

# Retrieve users from the primary database
users = User.where(age: 25)

# Update a user's information
user.update(name: 'Jane Doe')

# Delete a user
user.destroy
```

## Secondary Database Operations

```
# Create a new product in the secondary database
product = Product.create(name: 'Widget', price: 19.99)

# Retrieve products from the secondary database
products = Product.where(category: 'Electronics')

# Update a product's information
product.update(price: 24.99)

# Delete a product
product.destroy
```

## Running Migrations

When you're working with multiple databases, you need to run migrations separately for each database. To achieve this, you can specify the database connection when running migrations:

```
rails db:migrate          # Run migrations for the primary database
rails db:migrate RAILS_ENV=development_secondary # Run migrations for the secondary database
```

## Conclusion

In this article, we've explored how to connect and interact with multiple databases within a single Rails 5 application. By configuring the database.yml file, defining separate models for each database, and using the establish_connection method, you can seamlessly work with different databases in your application. Whether you're dealing with diverse data types or optimizing performance, Rails provides the flexibility you need to manage multiple databases effectively.