ActiveRecord Migration: terminology

By Mehdi Farsi

Mehdi Farsi

In the context of a database, a migration refers to the action of manipulating records (update, insertion, deletion, etc..).

But, in the context of ActiveRecord, a migration does not have the same meaning.

ActiveRecord Migrations

In the context of ActiveRecord, migrations represent the history of all the updates occurred in the database schema.

Indeed, a migration can concern:

  • The manipulation of a table
  • The manipulation of a field
  • The manipulation of a SQL extension
  • The execution of raw SQL that modifies the above elements

Each of these migrations is represented by a class that inherits from ActiveRecord::Migration

This class is associated to a timestamped file under the db/migrate folder.

$> ls -l db/migrate
total 1
-rw-r--r-- 20191114061825_create_admins.rb

Here, the db/migrate folder contains 1 migration.

This migration is timestamped as following:

20191114061825 => YYYYMMDDhhmmss

By default, each of these migrations will update the database schema.

ActiveRecord Schema

Our database schema is programmatically represented by a call to the ActiveRecord::Schema.define method.

This method takes a version as argument and a block that contains the representation of our database structure — using the ActiveRecord abstraction.

This database structure representation can be found in the db/schema.rb file.

For example, after the run of our migration, the schema looks like this

Note the version: 2019_11_14_061825 argument refers to the timestamp of our last executed migration — see the above section.

It’s possible to recreate the database structure related to the last executed migration by using the rails db:schema:load command.

This command simply executes the content of this file.


Now that we know the relation between our ActiveRecord migrations and the ActiveRecord Schema, let’s figure out why we use the migration terminology when, in this case, migrations simply refer to the update of our ActiveRecord schema.

Migration of the Schema

The reason of this terminology becomes very obvious when we understand the execution flow of our ActiveRecord migrations:

Each executed migration will:

  • Update the database
  • Update the ActiveRecord Schema
  • Update the ActiveRecord::Schema.define :version value.

So ActiveRecord migrations are so-called because each ActiveRecord migration migrates the ActiveRecord schema from a version (timestamp) to a new one.

In software engineering, we refer to this mechanism as Schema Migration.

This mechanism ensures to keep track of the history of the database structure evolutions at a programmatic level.

So now, you know why ActiveRecord refers to a database schema update as a migration.