# Activerecord multiple databases

**URL:** <https://www.ruby-forum.com/t/activerecord-multiple-databases/115550>\
**Category:** Rails\
**Created:** [September 26, 2007, 6:09am UTC](https://www.ruby-forum.com/t/activerecord-multiple-databases/115550 "2007-09-26T06:09:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dusty](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/a183cd/32.png) [@dusty](https://www.ruby-forum.com/u/dusty)\
**Post date:** [September 26, 2007, 6:09am UTC](https://www.ruby-forum.com/t/activerecord-multiple-databases/115550/1 "2007-09-26T06:09:01Z")

</div>

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)
