Edit migrations while developping a feature
Problem
Usually, when developping a new feature, I tend to write commits that are structured like this:
- Create model A
- Persist A from API
- Refactor handling bla bla bla
- Add field X to model A
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:
- Create a new migration that adds the field
- Edit the existing migration
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:
- I rebase interactively to the commit where I created the migration:
git rebase -i <commit>
- I rollback the migration:
rails db:rollback
- I edit the migration
- I run the migration again:
rails db:migrate
- 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!