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']
end

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

#Model definitions (current):

class Video < DatabaseCurrent
  belongs_to :user

  set_table_name :videos
end

class Photo < DatabaseCurrent
  belongs_to :user

  set_table_name :photos
end

class User < DatabaseCurrent
  has_many :videos
  has_many :photos

  set_table_name :user
end

class Tag < DatabaseCurrent
  set_table_name :tag
end

#Model definitions (old):

class FileDB < DatabaseOld
  set_table_name :file
end

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:


DatabaseCurrent.connection.execute("SQL")

That’s the tutorial for the day!

2 Replies to “Multiple DB connections in Rails/ActiveRecord”

  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.

    Like

  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.

    Like

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s