Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby on rails
rails

How to use ActiveRecord migrations in Rails 6

Muhammad Aghnus Jamil

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
SamleMigration class

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.

RELATED TAGS

ruby on rails
rails

CONTRIBUTOR

Muhammad Aghnus Jamil
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring