Skip to content

Instantly share code, notes, and snippets.

@mrnugget
Created September 8, 2017 09:06
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 mrnugget/83e9eed955650263faa9534c9e856ac5 to your computer and use it in GitHub Desktop.
Save mrnugget/83e9eed955650263faa9534c9e856ac5 to your computer and use it in GitHub Desktop.
Fixing a Rails migration in a previous commit

Fixing a Rails migration in a previous commit

Status Quo

We're sitting on a commit and a previous commit introduced a migration. The migration and the resulting db/structure.sql (or db/schema.rb) have been commited in <commit-to-be-fixed>.

Problem

If we would "just" go back to <commit-to-be-fixed> and edit the migration, we'd also need to update db/structure.sql. But our current database already already has the state of post-migration.

We'd need to rollback the migration, change it and run it again db/structure.sql again.

But that's not always possible with complex migrations.

What we need to do instead is to edit the migration, recreate the database, run the migration and then dump the db/structure.sql.

Step-by-step

  • Start an interactive git-rebase:
    git rebase -i <parent-commit-of-commit-to-be-fixed>
    
  • Change the line with <commit-to-be-fixed> to look like this: edit <commit-to-be-fixed>
  • Save and watch git rebase stop at <commit-to-be-fixed>
  • Now we need to reset the db/structure.sql to the state of parent-commit (pre-migration):
    git reset HEAD^ db/structure.sql
    
  • Drop the database and recreate it from scratch (so the structure in the database matches the one of the parent-commit):
    bundle exec rake db:drop db:setup
    
  • Fix the migration by editing it
  • Run the migration again:
    bundle exec rake db:migrate
    
  • Now the db/structure.sql should've been dumped and contain the changes that result from the fixed migration
  • Use git add to add the changes in the migration and db/structure.sql
  • Finish the rebase: git rebase --continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment