Michael Buffington

Multiple Databases in Rails

Monday, July 25 2005

I just spent a while trying to figure how to have a single Model in my Rails application talk to another table in another database. The solution is so staggeringly simple I’m embarrassed that I had to figure it out nearly by mistake:

1
2
3
class YourModel < ActiveRecord::Base
def self.table_name () “dbname.tablename” end
end

The user name and password required to access the other database need to be the same as the user name and password on the database you’ve set up in your databases.yml file. After that, you’re simply taking advantage of MySQL’s (or most RDBMS servers’) ability to access other databases on the same server, provided the current user has the rights to do so.