Skip to content
This repository


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Simple Rails plugin for switching context to a different database

branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time


DB Context

There are quite a lot of articles out there about connecting to multiple databases within a Rails app.

A lot of them require a good bit of mixing around with models and things. I wanted to just be able to add a field to database.yml and then call that context on demand.

For example:

db_context(:other_database) do

This simple Rails plugin allows just that.


First of all, define your other database in config/database.yml

  adapter: sqlite3
  database: db/development.sqlite3
  timeout: 5000
  adapter: sqlite3
  database: db/other_development.sqlite3
  timeout: 5000
  # ... and so forth for your other environments.

Then, set up your model as usual:

class Article < ActiveRecord::Base

Then, anywhere in your code where you want to connect to the “other_development” database, just wrap your call with “db_context”

@articles = db_context(:other) do


This is very hacky. I created it just so I could use the nice block syntax for choosing the database scope. If you want migrations to work, you’ll need to create new environment files in config/environments/ for them.

Also: I didn’t build this for production: the Rails app that I’m abstracting from does use only one database: I’m using this plugin in some background tasks for rebuilding data.

However, it is a really simple, quick way around the problem, that doesn’t involve too much messing about.



./script plugin install git://

About me

I’m Paul Campbell. I’m an avid web developer. Follow my ramblings at

Follow me on Twitter

Copyright © 2009 Paul Campbell, released under the MIT license

Something went wrong with that request. Please try again.