strapyourself.in and flouri.sh

Using and testing multiple databases in rails part 2

May 30th, 2007

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:

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

To have a migration run on a different database

class AddOtherDbStuff < ActiveRecord::Migration
  def self.database_model
    OtherDbBase
  end
end

Sample config/use_db.yml file:

db1:
  prefix: db1_
db2:
  prefix: db2_ 

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

rake test

To have fixtures load into a different database:

# 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.

# 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.

Want to download this plugin? Download from ELC's SVN repository OR:

./script/plugin install https://wush.net/svn/public/use_db

Originally posted on ELC

See ELC's other Rails Plugins

Sorry, comments are closed for this article.

original design by gorotron ported by railsgrunt powered by mephisto