Specify Up and Down Operations

Learn how to use up and down operations.

In the last section, we created a migration that altered data and structure, but we left out an important step. In its current form, this migration can’t be rolled back.

Ecto can’t reverse the removal of a column because it wouldn’t know what type it should be restored back to. We certainly can’t expect Ecto to figure out how to reverse the data transformation we did between compositions and compositions_artists. We need to specify the rollback instructions ourselves.

The up and down functions

In cases like these, we write the migration differently. Instead of providing a single change function, we write an up function and a down function to handle the migration going forward and rolling back. Let’s rewrite the migration so it can be rolled back.

Right now, our change function has all the logic we need. All that’s left is to rename the function from change to up. We still need to write the down function, though.

Here’s how we might do it.

Get hands-on with 1200+ tech skills courses.