Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

Using ActiveRecord with multiple databases

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}" }

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}"

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

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *