CommonThread - Our Blog

Tip: Rails Default Data Migrations

Written By: Anthony Crumley

February 24th, 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)

1 Response to “Tip: Rails Default Data Migrations”

  1. Sydney Delacruz Says:
    ouqx127w37bxh21g

Leave a Reply