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