Activerecord multiple databases

So, I was looking for a setup that would allow me to easily query
multiple databases and not have to re-write my customer finder type
queries. Here is what I came up with and it seems to be working for
me in my very basic tests so I thought I’d share. Just posting it in
case this helps anyone else trying to do the same thing.

I’m using this with activerecord, but not rails, so there may be some
adjustments needed if you are trying to incorporate this into rails.

module Project
DBCONFIG = YAML::load(File.open(‘database.yml’))

module ConnectionFactory
class DB1 < ActiveRecord::Base
self.establish_connection(Project::DBCONFIG[‘db1’])
end
class DB2 < ActiveRecord::Base
self.establish_connection(Project::DBCONFIG[‘db2’])
end
end

module ClassMethods
module SomeClassName
def long_query(name)
r = find_by_sql [“SELECT …”,name]
r.first unless r.empty?
end
end
module SomeOtherClass
def long_query(number)
r = find_by_sql [“SELECT …”,name]
r.first unless r.empty?
end
end
end

end

module DB1
class SomeClassName < Project::ConnectionFactory::DB1
set_table_name “thetable”
extend Project::ClassMethods::SomeClassName
end
class SomeOtherClass < Project::ConnectionFactory::DB1
set_table_name “theothertable”
extend Project::ClassMethods::SomeOtherClass
end
end

module DB2
class SomeClassName < Project::ConnectionFactory::DB2
set_table_name “thetable”
extend Project::ClassMethods::SomeClassName
end
class SomeOtherClass < Project::ConnectionFactory::DB2
set_table_name “theothertable”
extend Project::ClassMethods::SomeOtherClass
end
end

queries db1

DB1::SomeClassName.long_query(name)
DB1::SomeOtherClass.long_query(name)

queries db2

DB2::SomeClassName.long_query(name)
DB2::SomeOtherClass.long_query(name)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs