How to solve migration problems in Rails?

MIJIMO 米佶摩
Lecture Notes
Published in
2 min readJan 8, 2018
A migration file to alter user

A problem within a migration file causes the migration to get stuck in the middle.

What does that mean?

Let’s say, there’s mistake within your migration file. This could be a typo, or a logical mismatch (trying to rename a non-existing column within a table), or so on. When you run your migration, rails db:migrate, all the lines until the mistaken line will be executed successfully, but the migration will fail at that point. Your migration is not fully UP state. It’s somewhere in between.

You may try to reset migrations rails db:migrate VERSION=0, but most likely that will fail either, as the changes you’ve made previously cannot be taken to DOWN state either (because some of the changes you’ve made are UP state, but not all).

Your migration gets stuck in middle state, neither UP nor DOWN.

Here’s how to solve such a migration problem:

  1. First fix the mistaken line (obviously)
  2. Temporarily comment out the lines that were executed successfully with a #
  3. Run the migration again
First 3 lines are commented out

You will be able to run the missing migration lines, and all of the migration will be UP state. Now you can reset back to VERSION=0 if you’d like.

Suggestions

There are some piece of advice to consider:

Make migration files small and concise

Do not put 6 different table modifications into 1 migration file. Instead, create separate migration files for each.

Make sure migration files are correct

Especially before moving to production stage, make sure you have your migration files are 100% flawless.

Fix the database directly

That’s a possible option either. If you’re confident with working on databases (a good grab of SQL), you can directly modify the errors on the database. Although you still need to fix the errors on your migration file, if you’re planning to use it later.

--

--