Connecting to Multiple Databases Using ActiveRecord

October 17th, 2009 by Radar

You 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: , ,

4 Responses to “Connecting to Multiple Databases Using ActiveRecord”

  1. mlambie Says:

    Very cool Radar. I especially like extending AR::Base.

  2. almost effortless » Weekly Digest, 11-6-09 Says:

    [...] 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 [...]

  3. AL Says:

    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 mcks

    I place the mck.rb file on the lib folder.Any help would be appreciated

  4. Nathan Zook Says:

    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.

Leave a Reply