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

Let us know how we can contact you.

Thank you!

We'll respond shortly.

  • Blog Navigation
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.

  • BIGmike

    Does the child class require explicit table name setting or will the table be set to the child’s default pluralized name?

    • Slava K.

      It will be set to default pluralized name

  • Luna Das


Share This