Connecting to Multiple Databases Using ActiveRecord
October 17th, 2009 by RadarYou can call establish_connection with the key that points to another database config in your config/database.yml file
class Person < ActiveRecord::Base establish_connection(:hr) end
class Ticket < ActiveRecord::Base establish_connection(:bug_tracker) end
If you have a whole bunch of models that need to connect to another database:
class HR < ActiveRecord::Base establish_connection(:hr) end class People < HR # ... end class Resource < HR # ... end
Tags: activerecord, rails, ruby

October 30th, 2009 at 5:00 pm
Very cool Radar. I especially like extending AR::Base.
November 7th, 2009 at 6:57 am
[...] Connecting to Multiple Databases Using ActiveRecord You can call establish_connection with the key that points to another database config in your config/database.yml file [...]
November 10th, 2009 at 7:11 am
Good tip. I was able to use establish_connection on the model class, but when I tried to use the extension example:
class MCK < ActiveRecord::Base establish_connection(:Mydb) end
class Mckuser < MCK end
I get an error:
Table ‘Mydb.mcks’ doesn’t exist: SHOW FIELDS FROM
mcksI place the mck.rb file on the lib folder.Any help would be appreciated
February 20th, 2010 at 5:25 am
AL: Here’s what you need: class HR < ActiveRecord::Base @abstractclass = true establishconnection(:hr) end
My current employer is using four databases (on two servers). I do the following: class ApplicationModel < ActiveRecord::Base @abstract_class = true
def self.setupconnection basename = self.name.sub(/ConnectBase$/, ”) establishconnection(ActiveRecord::Base.configurations["#{basename.underscore}#{RAILSENV}"]) end end
class MyDBConnectBase < ApplicationModel
@abstractclass = true setupconnection
end
Then all of my models inherit from one of the MyDBConnectBases.