Rails: Managing Migrations

Migration is a tool for managing databases within Ruby on Rails. The tool itself only offers a few features but people use it in a variety of different ways including:

  • Creating new tables.
  • Adding columns to an existing table.
  • Dropping a specific table.
  • Adding data to a table.
  • Changing the datatype of a specific column.
  • Rolling back to a previous migration.

Most important of all, the /migration folder can be used as a ledger to help you keep a record of the changes you've made to your database.

Said differently, Schema.rb will tell you what your database currently looks like but migrations will explain how you got there.


Getting Started

Whenever I download a project from Github, I first check the status of migrations to see if anything looks weird

rails db:migrate:status

Add a new attribute/column to your model and include an index.

rails g migration add_column_to_table attribute:string:index

Add an index to an existing model/table.

rails g migration add_index_to_users email:string:index

Modifying a column or relationship

If you have a table and you want to add a new column to the table, use this command-line

rails g migration add_attribute_to_model

Source

Delete and Recreate a Database

Purge is an extreme version of drop. Using purge, you will delete the table, the database and even the schema. I use this to guarantee my database is destroyed and rebuilt.

rails db:purge db:create db:migrate

Source

Dropping a Database

rails db:drop

Resetting Your Database

rails db:reset

Rolling Back

Rollback to your previous version

rake db:rollback

Rollback to a specific version

rails db:migrate:down VERSION=20100905201547

How to rollback a migration