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

3 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

Leave a Reply