Multiple Database Connections in Ruby on Rails

We have a client that already has some database replication going on in their deployment and needed to have most of their Ruby on Rails application pull from slave servers, but the few writes would go to the master, which would then end up in their slaves.

So, I was able to quickly extend ActiveRecord with just two methods to achieve this. Anyhow, earlier today, someone in #caboose asked if there was any solutions to this and it prompted me to finally package this up into a quick and dirty Rails plugin.

Introducing… Active Delegate!

To install, do the following:

cd vendor/plugins;
piston import http://svn.planetargon.org/rails/plugins/active_delegate
```text
Next, you'll need to create another database entry in your
`database.yml`.

```yaml
login: &login
  adapter: postgresql
  host: localhost
  port: 5432

development:
  database: rubyurl_development
  <<: *login

test:
  database: rubyurl_test
  <<: *login

production:
  database: rubyurl_servant
  <<: *login

# NOTICE THE NEXT ENTRY/KEY
master_database:
  database: rubyurl_master
  <<: *login
````ruby
At this point, your Rails application won't talk to the
`master_database`, because nothing is being told to connect to it. So,
the current solution with Active Delegate is to create an ActiveRecord
model that will act as a connection handler.

````ruby
# app/models/master_database.rb
class MasterDatabase < ActiveRecord::Base
  handles_connection_for :master_database # <-- this matches the key from our database.yml
end  
```text
Now, in the model(s) that we'll want to have talk to this database,
we'll do add the following.

````ruby
# app/models/animal.rb
class Animal < ActiveRecord::Base
   delegates_connection_to :master_database, :on => [:create, :save, :destroy]
end

Now, when your application performs a create, save, or destroy, it’ll talk to the master database and your find calls will retrieve data from your servant database.

It’s late on a Friday afternoon and I felt compelled to toss this up for everyone. I think that this could be improved quite a bit, but it’s working great for the original problem that needed to be solved.

If you have feedback and/or bugs, please send us tickets.

Hi, I'm Robby.

Robby Russell

I run Planet Argon, where we help organizations keep their Ruby on Rails apps maintainable—so they don't have to start over. I created Oh My Zsh to make developers more efficient and host the Maintainable.fm podcast to explore what it takes to build software that lasts.