Table of contents:
- migration tasks
- new change syntax
- using models in a migration
- reversible migrations
- revert command
A lot of this stuff is available in the Rails migration guides: http://guides.rubyonrails.org/migrations.html
These helpful tasks don't show up with rake -T db:
You can rerun a migration you are working on with rake db:migrate:redo
rake db:migrate:redo STEP=2
rake db:rollback STEP=2
rake db:forward STEP=2
You can explicitly run the up
or down
direction of a migration:
rake db:migrate:down VERSION=20140101000000
rake db:migrate:up VERSION=20140201000000`
You can use STEP
for relative moves
During development, tables change as you figure out how your data model is shaped. When you're working with multiple developers, it's a pain to coordinate everyone rolling back and removing migrations that describe older versions of your model.
It's best to always move forward with your migrations and use reverts and reversible migrations to structure your database as you like it.
Let's say we have a migration that creates a table that we later want to
restructure. It's possible to just drop the table in the next migration
and start over, but the original migration probably adds things like
indexes or foreign key constraints that need to be removed also. You can
use the revert command to call the down
action from inside your own
migration. This keeps the migrations contained as discrete elements,
rather than a jumble of piecemeal SQL instructions.
The dreaded NO FILE in your migration history. It turns out this is pretty easy with Git, you can just log for the revision number.
$ git log --patch -- "20140101000000_*.rb"
Then checkout the file and down
it.
$ git checkout <SHA1> -- "20140101000000_*.rb"
$ rake db:migrate:down VERSION=20140101000000