How to access multiple databases with rails 1 comment

Posted by stephane Sat, 31 May 2008 17:08:00 GMT

I know it exists other information about this, but I want to summarize here the practise I use in several project now. It takes 4 steps:

  • configure your database.yml
  • create an abstract class for connection
  • create new models within a module
  • interact the 2 databases

1. Configure your database.yml

This is the same as you create production or development connection, just give it a specific name:

other_database_connection:
    adapter: postgresql
    encoding: utf8
    database: database_name
    username: user
    password: password
    host: localhost

2. Create an abstract class for connection

Then create an abstract class you will inheritate by your new classes:

class External < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :other_database_connection
end

3. Create new models within a module

To make it easier to use and cleaner, create a subfolder OtherDatabase and then create in this folder your new classes (for each table you need) as following:

class OtherDatabase::NewClass1 < External
end

4. How to interact the 2 databases

Once you have created your new classes, you can simply access it using the module prefix:

new_object = OtherDatabase::NewClass1.new
.
result = OtherDatabase::NewClass1.find(:all)

Conclusion

That’s all, submodule is not really necessary but keeps your model folder cleaner. Any suggestion to improve this practise ?