1. Skip to navigation
  2. Skip to content

The ELC Community Blog

A knowledge exchange on Ruby on Rails and Agile Development


Using and testing multiple databases in rails part 2

by stevend on May 30, 2007

ELC Plugins

I previously published a plugin on this blog that allows you to easily use, test, and migrate multiple databases in rails.

Since then, I've found numerous problems and areas that could be improved about this process. Here they are:

  • All databases are automatically cloned through rake tasks that are dependent on standard "rake test" commands.
  • Transactions are properly set up across ALL open connections during testing (if transactional fixtures are enabled)
  • This plugin is now in use in a large-scale production environment!
  • Compatibility with my preload fixtures plugin to make fixture loading super fast and transactional (coming soon to this blog)

Examples of how to use it:

To point a model at a different database:

   1  <pre>class OtherDbBase < ActiveRecord::Base
   2    use_db :prefix => "otherdb"
   3    # will look for otherdb_development, otherdb_test, etc. in database.yml
   4  end</pre>

To have a migration run on a different database

   1  <pre>class AddOtherDbStuff < ActiveRecord::Migration
   2    def self.database_model
   3      OtherDbBase
   4    end
   5  end</pre>

Sample config/use_db.yml file:

   1  <pre>db1:
   2    prefix: db1_
   3  db2:
   4    prefix: db2_ </pre>

To run tests across multiple databases (requires file config/use_db.yml):

   1  <pre>rake test</pre>

To have fixtures load into a different database:

   1  <pre># Do nothing!  Just name the fixture the same name as the model is represents (in our case it would be other_db_bases.yml), and the fixture loader will use that class's database connection to insert fixtures.
   2  
   3  # I realize this might limit some people, especially those with habtm fixutres on other DBs (since there's no model).  I'd love your input on where we should specify which DB connection a fixture should use to load itself.</pre>

Want to download this plugin? Download from our SVN repository OR:

   1  <pre>./script/plugin install https://wush.net/svn/public/use_db</pre>

See our other Rails Plugins

Comments

Add a comment


home | services | Ruby on Rails Development | code | blog | company