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

July 2017
S M T W T F S
« Sep    
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

Posts by Month

Posts by Category