Exploring Multiple Database Support in Rails

Working with multiple databases is a common requirement in many Rails applications. Whether you need to interact with legacy databases, implement data sharding strategies, or separate different types of data, Rails provides robust support for managing multiple databases.

Configuring Multiple Databases:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
   # config/database.yml

   development:
     primary:
       adapter: postgresql
       database: my_app_development
       username: username
       password: password

     legacy:
       adapter: mysql2
       database: legacy_db
       host: legacy_host
       username: legacy_user
       password: legacy_password

Establishing Connection:

1
2
3
4
5
6
7
   # config/initializers/database_connections.rb

   primary_db_config = Rails.configuration.database_configuration[Rails.env]['primary']
   legacy_db_config = Rails.configuration.database_configuration[Rails.env]['legacy']

   primary_db = ActiveRecord::Base.establish_connection(primary_db_config)
   legacy_db = ActiveRecord::Base.establish_connection(legacy_db_config)

Model Configuration:

1
2
3
4
5
6
7
8
9
10
11
12
13
   class User < ActiveRecord::Base
     self.abstract_class = true
   end

   class PrimaryUser < User
     self.table_name = 'users'
     on_db :primary
   end

   class LegacyUser < User
     self.table_name = 'legacy_users'
     on_db :legacy
   end

Querying and Transactions:

1
2
3
4
5
6
7
8
9
10
   PrimaryUser.on_db(:primary).where(name: 'John')
   LegacyUser.on_db(:legacy).find_by(username: 'johndoe')

   User.on_db(:primary).transaction do
     # Perform operations involving the primary database
   end

   User.on_db(:legacy).transaction do
     # Perform operations involving the legacy database
   end