Using ActiveRecord with multiple databases

February 14, 2013 John Barker

At Pivotal I’ve been working on a project which uses two databases. Doing some quick searching we came up with a rather naive solution, this quick mixin:

module SecondDatabaseMixin
  extend ActiveSupport::Concern
  included { establish_connection "db2_#{Rails.env}" }
end

It didn’t become obvious what was wrong with this until we added one too many models. Suddenly we started getting complaints from the database that we had too many connections open.

Reading the documentation for ActiveRecord it became clear that the correct way to share connections is to use inheritance. This was the solution we came up with:

class SecondDatabaseModel < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "db2_#{Rails.env}"
end

Now any model that inherits from SecondDatabaseModel gets a connection to the correct database, and we only have as many connections as needed.

About the Author

Biography

More Content by John Barker
Previous
What happened to stdout on CI?
What happened to stdout on CI?

We were struggling for a bit yesterday trying to figure out why the few puts statements in our tests weren’...

Next
A Pair of Shoes to Fill
A Pair of Shoes to Fill

I woke up in the mid morning to a heavily blinded room and crept outside hoping not to wake anyone. I fumbl...

Enter curious. Exit smarter.

Learn More