Skip to content

Instantly share code, notes, and snippets.

@timuruski
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timuruski/9940118 to your computer and use it in GitHub Desktop.
Save timuruski/9940118 to your computer and use it in GitHub Desktop.
Notes for a talk about Rails migrations

The Migratory Habits of Rails Developers

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

Migration tasks

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

Always move forward with your migrations

Cleaning up development thrash

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.

Using revert to rebuild a table

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.

Migrating data from one table to another

Adding seeds and fixtures to your app

Finding lost migrations

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment