Source: unsplash.com

ActiveRecord Migration: terminology

Why do we refer to database structure updates as migrations in ActiveRecord?

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.

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this link! 🙏

Thank you for your time!

ActiveRecord Migrations

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

Indeed, the different scopes of a migration are:

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 ActiveRecord::Schema.define . This method takes a version as argument and a block that contains the representation of our database structure — using the ActiveRecord abstraction. This schema can be found in the db/schema.rb file.

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

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 understand 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

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.

Voilà!