How to use ActiveRecord migrations in Rails 6

Migrations are a convenient and easy way to make consistent changes to our database structure over time. This methodology is compatible with the Agile and XP methods used by Rails developers worldwide.

Migration is the subclass of ActiveRecord::Migration, which overrides the two needed methods:

  • self.up
  • self.down

Structure of rails ActiveRecord migrations

class SampleMigration < ActiveRecord::Migration
        def self.up
        end

        def self.down
        end
end

We can perform the following operations in self.up and self.down methods:

  • Create tables and indexes
  • Add data
  • Manipulate models and so on

In both practice and theory, the concept is straightforward:

  • The self.up method definition contains the actions we wish to migrate to the next version of the schema.
  • Put anything we need to do to undo the change in the self.down method.

Code example

Let’s look at the code below:

class SampleMigration < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.column :name, :string
end
end
def self.down
drop_table :people
end
end

Code explanation

  • Line 1: We created the SampleMigration subclass from the ActiveRecord::Migration.
  • Line 2: We implement the self.up method.
  • Lines 3 to 4: We use SampleMigration to create a table people with a string column named name.
  • Lines 8: We implement the self.down method.
  • Lines 9: We use SampleMigration to drop the people table.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved