Accueil À propos Contact / Devis
Back to all posts
January 2024 rails

Edit migrations while developping a feature

Problem

Usually, when developping a new feature, I tend to write commits that are structured like this:

When I create model A, even though I try to think about all the fields I need, I often forget some. So I run into a problem where I need to add a field to my model, but I already have a migration that creates the table. In this case I can:

Adding a new migration feels to me like adding clutter for someone who would read these commits or review a Pull Request. So I tend to edit the existing migration. But then I run into a problem: I already ran the migration, so I need to rollback it, edit it, and run it again. This gets even trickier because usually, the migration is located a few commits back in the history. This is a lot of work for a simple change.

Solution

I found a solution that works for me: I use interactive rebasing to edit the migration. Here is how it works:

  1. I rebase interactively to the commit where I created the migration: git rebase -i <commit>
  2. I rollback the migration: rails db:rollback
  3. I edit the migration
  4. I run the migration again: rails db:migrate
  5. I continue the rebase: git rebase --continue

With this, I can edit the migration without creating a new one, all while keeping my commits clean.

What might seem a bit tedious has in fact become a habit for me. I find it very useful to keep my commits clean and readable. I hope this can help you too!