Rails: How to SANELY connect to an old database


Categories: GeekStuff

The world is full of helpful people advising that, to connect a model to another database, you just do:

class LegacyFoo < ActiveRecord::Base establish_connection “foo” end

This is great advice, and it works. But if you have multiple models using the legacy database, it turns out there’s a problem: The establish_connection is per-class, meaning you have one established connection for each model. This means that you chew up allowable connections many times faster than you expect to.

Thanks to a very helpful IRC user (thanks, Scientz!), I now have a solution for this:

1. Create a new class:

class LegacyDatabaseModel < ActiveRecord::Base
  establish_connection "foo"

Store this in app/models/legacydatabasemodel.rb.

2. Convert all your legacy records to inherit from it:

class LegacyFoo < LegacyDatabaseModel

Now all your legacy records are sharing a single connection.