The example here splits Author information out of an existing Post model.
The trouble with a data migration that moves information is that its models are defined for the “new” schema, but has to operate on data stored in the “old” schema. I see two alternative approaches:
- Use inline models to represent your old schema
- Run the migration in stages (1: add new model, copy data, 2: remove old fields)
Points of interest and gotchas:
- Migrations are just more Ruby code. Require the migration file and test it just like any other code you write.
- Factory girl makes it just as easy to seed “old” data as “new”. Just use Factory.build, and in Rails3, use Model.save(:validations=>false) to skip validation checks.
- Use ActiveRecord::Migration.up_without_benchmarks to suppress output from migrations. I didn’t find any documentation for this method, though up_with_benchmarks shows up in APIDock.
We’ve been thinking about the robustness of ActiveRecord migrations for a few weeks now. Look for more detailed discussion of migrations in general in a follow on post.