Multiple Databases on Rails
I have been loving work recently.
A fellow geek and I have embarked on a voyage splicing a new technology into a legacy system and it's mosaic or underlying programs. Our architecture is a little funny, in the strange way, not the humorous way. Therefore, I've been presented with a never ending set of hurdles in making rails do what I need it to do.
Which is just the way I like it.
The first order of business was to get rails to talk to several different dataservers and to connect to different databases within each one. It would appear that the magic to make it all happen is to create your own base record that will connect to different databases. To show how easy it is:
# cat lib/different_database_base.rb
class DifferentDatabaseBase < ActiveRecord::Base
establish_connection (:host=>"some_other_server",
:database=>"another_database",
:username=>"jsmith",
:password="letmein")
end
# cat app/model/some_class.rb
class SomeClass < DifferentDatabaseBase
end
That's all you need. Now in your controllers and views, any SomeClass objects will be retrieved through the connection to another_database. We didn't just come to this conclusion, there was a lot of bad before it got this good.
And now, I'm a believer.




