DEV Community

Cover image for Learning Rails #2 - Migrations
Jesse Sousa
Jesse Sousa

Posted on

Learning Rails #2 - Migrations

The role of these series, is to be used as a refresher and a place where beginners can discuss.
If you're also learning (or intend to learn) Rails, I highly recommend that you follow the Getting Started section of the Rails Guides.

When creating a model, a migration file is also generated. You should see a file like 20130924230504_create_users.rb in thedb/migrate folder (this giant number is a timestamp). This is the migration file of your model and if you click it, you see that inside that are all attributes that you made and its types.
After creating a model you have to run the migration, in order to update the database, creating a new table for the model.

What is a Migration?

A Migration basically is a script that will have all the code needed to change your database. Basically every change you make to the database should be through a migration.

For example: Let's say you created a model for users, and ran its migrations, then you realize you forgot the email attribute, you can solve this problem by creating a new migration file.

rails generate migration AddEmailToUsers
Enter fullscreen mode Exit fullscreen mode

And in the migration file, you can add any changes, in our case we need to add an email attribute, so we'll do:

# In the migration file
class AddEmailToUsers < ActiveRecord::Migration[7.0]

  def change
    add_column :users, :email, :string

Enter fullscreen mode Exit fullscreen mode


rails db:migrate
Enter fullscreen mode Exit fullscreen mode

Now all migrations will run, hence the database will be updated.

How to use Migrate and Rollback

  • rails db:migrate
    As we've seen before, this will run all the migrations.

  • rails db:rollback
    It will run the inverse command for everything a migration did, sometimes you'll need to write it yourself check the documentation for more information.

By default, the commands above will run all the migrations you have, using the timestamp to track the order of when which script should run. To run only the migrations you want, use the STEP parameter. Ex.: rails db:migrate STEP=2, this will run only two migrations files.

Top comments (0)