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.
Whenever I download a project from Github, I first check the status of migrations to see if anything looks weird
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
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
Dropping a Database
Resetting Your Database
Rollback to your previous version
Rollback to a specific version
rails db:migrate:down VERSION=20100905201547