Posts filed under ‘Ruby’

Multiple ActiveRecord connections without Rails

Here is a little trick that allows having connections to multiple databases with pure ActiveRecord.

First, a little recap. Here is the code for making a single connection:

require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql',
  :database => $env[:db_name],
  :username => $env[:db_user],
  :password => $env[:db_pass],
  :host     => $env[:db_host])

class MyTable < ActiveRecord::Base
end

The nice thing with this approach is that any additional class will automatically reuse the defined connection.

However, if we need to have multiple connections the approach is a little different:

require 'active_record'

ActiveRecord::Base.configurations["db1"] = {
  :adapter  => 'mysql',
  :database => $env[:db1_name],
  :username => $env[:db1_user],
  :password => $env[:db1_pass],
  :host     => $env[:db1_host]
}


ActiveRecord::Base.configurations["db2"] = {
  :adapter  => 'mysql',
  :database => $env[:db2_name],
  :username => $env[:db2_user],
  :password => $env[:db2_pass],
  :host     => $env[:db2_host]
}

class Table1 < ActiveRecord::Base
  establish_connection "db1"
end

class Table2 < ActiveRecord::Base
  establish_connection "db2"
end

This approach allows defining any number of database connections and any number of tables on those connection. It also allows adding connections and classes dynamically based on some runtime information. The only drawback is that in each class you are required to define which connection needs to be used.

September 26, 2010 at 2:37 pm Leave a comment


Calendar

May 2017
S M T W T F S
« Sep    
 123456
78910111213
14151617181920
21222324252627
28293031  

Posts by Month

Posts by Category