CommonThread

Tip: Rails Default Data Migrations

Posted by anthony crumley, Sun Feb 24 22:04:00 UTC 2008

Data migrations for default values can be messy. When creating default data, migrations can get lengthy and cluttered with…well…data. Down the road they can cause problems when the model they depend on has been removed.

The clutter issue can be resolved with Fixtures.create_fixtures and a YAML file containing the default data. The deleted model issue can be resolved by defining the model in the migration (Rails Recipes #30).

Example:


require "active_record/fixtures" 

class CreateCategoryData < ActiveRecord::Migration
  class Category < ActiveRecord::Base; end

  def self.up
    Fixtures.create_fixtures(
      "db/fixtures", 
      "categories", 
      :categories => "CreateCategoryData::Category" 
    )
  end

  def self.down
    Category.delete_all
  end
end

Correction: I left off the class_names hash from create_fixtures. This parameter causes Fixtures to use the locally scoped model rather than the global one, e.g. CreateCategoryData::Category rather than Category. (2/25/2008)

Filed Under: Ruby on Rails | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.




Categories