What alternative do you suggest for using models in migrations? I was in several situations where I had to not only change the underlying db structure but change the contained data, too.
Data changes, especially moving data around, are almost always rake task-worthy in my experience.
The other side of that, populating large amounts of seed data into new databases, is a difficult task no matter the method; seed_fu attempted to deal with it, but it’s not an optimal solution and pretty old. I’m not even sure if it works anymore. It’s worse if you need the seed data to be from a legacy database in tests (e.g. a nutritional database). Reloading lots of data each time a clone_structure_to_test is done makes your tests very slow.
I break down migrations into three kinds; structural (tables, columns, indices, etc.), data (pre-populating tables, etc.) and procedural (moving data around, recalculating counts, etc.). The first is what I strive to limit migrations to. I feel like there should be a good answer for the second and Rails 3.0 has a ‘Simplest Thing That Can Work’ feature in Rails commit #4932f7b. The third, I try to relegate to rake tasks that are usually run once, on deployment of the branch.
The procedural tasks don’t need to be run when building a fresh database, because there isn’t legacy data to correct. That’s why you can usually define the model in the migration to force it to work even if the real model is gone or renamed; there’s no data, so the operations often don’t matter. If they don’t NEED to be run when building a fresh database, I try not to put them in the migrations.
It’s not ‘hard and fast’, because I usually work in startups to small companies, where dogma doesn’t work so well. Imagine, though, a large and thin piece of foam. It’s flexible, and you can make it into all sorts of shapes, and yet it’s simple. Each time you add code that makes reasonable changes in the future painful, it’s like putting a thin glass rod into the foam. It’s still flexible, but there’s some bends you can’t do without breaking. Add too many and you’ve got an inflexible and brittle object, no matter how dynamic the base material is.
The fear of breaking things by changing the code is deeply demotivating for everyone.
I know I waterboarded that analogy, but hopefully it makes sense…
— Morgan Schweers, CyberFOX!