Multiple DB connections in Rails/ActiveRecord

You might often want to connect to different databases using ActiveRecord. Here’s how you do it:

#DB definitions:

class DatabaseCurrent < ActiveRecord::Base
  self.abstract_class = true
  establish_connection settings['database']

class DatabaseOld < ActiveRecord::Base
  self.abstract_class = true
  establish_connection settings['database2']

#Model definitions (current):

class Video < DatabaseCurrent
  belongs_to :user

  set_table_name :videos

class Photo < DatabaseCurrent
  belongs_to :user

  set_table_name :photos

class User < DatabaseCurrent
  has_many :videos
  has_many :photos

  set_table_name :user

class Tag < DatabaseCurrent
  set_table_name :tag

#Model definitions (old):

class FileDB < DatabaseOld
  set_table_name :file

Pretty easy. The only thing to note is that you should set_table_name, otherwise, AR chokes up. Also, often you want to directly play directly with SQL. Unfortunately, ActiveRecord::Base.execute doesn’t work any longer (coz it doesn’t have a connection), but you can do it this way:


That’s the tutorial for the day!

2 responses

  1. ActiveRecord/Ruby afaik by default maintains (persists) a single connection for a thread and across all statements executed by that thread (at least for the MySQL driver).

    Multiple threads have their own connections. You have to go through a non-trivial process to make multiple threads share a connection but this is often a non-issue since Ruby/Rails doesn’t have that many threads for any deployment.

  2. Finally, a code snippet on your site which I can understand atleast partially! 😀

    AR sounds very similar to ADO’s recordsets.

    Got some doubts here.

    Lets take the case where we are connecting to an Oracle database, which doesn’t like multiple connections, due to max load reasons.

    Does AR connect and disconnect for every .execute instance?

    Or is it possible to maintain a single connection throughout the time during which we use the client app? Thats a standard we follow while doing ADO in VB/.Net.

Leave a Reply

Create a website or blog at