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.

Advertisements

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


Calendar

November 2017
S M T W T F S
« Sep    
 1234
567891011
12131415161718
19202122232425
2627282930  

Posts by Month

Posts by Category