🔥 Multiple databases for Rails
One of the easiest ways to scale your database is to move large, infrequently-joined tables to a separate database. ActiveRecord supports multiple databases, but Rails doesn’t provide a way to manage them. Multiverse changes this.
Works with Rails 4.2+
Add this line to your application’s Gemfile:
gem 'multiverse'In this example, we’ll have a separate database for our e-commerce catalog that we’ll call catalog.
The first step is to generate the necessary files.
rails generate multiverse:db catalogThis creates a CatalogRecord class for models to inherit from and adds configuration to config/database.yml. It also creates a db/catalog directory for migrations and schema.rb to live.
rails and rake commands run for the original database by default. To run commands for the new database, use the DB environment variable. For instance:
Create the database
DB=catalog rake db:createCreate a migration
DB=catalog rails generate migration add_name_to_productsRun migrations
DB=catalog rake db:migrateRollback
DB=catalog rake db:rollbackAlso works for models
DB=catalog rails generate model ProductThis generates
class Product < CatalogRecord
endFor web servers that fork, be sure to reconnect after forking (just like you do with ActiveRecord::Base)
In config/puma.rb, add inside the on_worker_boot block
CatalogRecord.establish_connection :"catalog_#{Rails.env}"In config/unicorn.rb, add inside the before_fork block
CatalogRecord.connection.disconnect!And inside the after_fork block
CatalogRecord.establish_connection :"catalog_#{Rails.env}"Rails fixtures work automatically.
Database Cleaner supports multiple connections out of the box.
cleaner = DatabaseCleaner[:active_record, {model: CatalogRecord}]
cleaner.strategy = :transaction
cleaner.cleaning do
# code
endView the changelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs and submit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features