0
0
Ruby on Railsframework~5 mins

Why migrations version the database in Ruby on Rails

Choose your learning style9 modes available
Introduction

Migrations keep track of changes to the database so Rails knows what has been done and what still needs to be done.

When adding a new table to store user data
When changing a column type in an existing table
When removing a column that is no longer needed
When fixing a mistake in a previous database change
When sharing database changes with other developers
Syntax
Ruby on Rails
class AddAgeToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :age, :integer
  end
end
Each migration file has a version number based on timestamp to order changes.
Rails uses this version to know which migrations have run and which are pending.
Examples
This migration creates a users table and is identified by the timestamp 20230610120000.
Ruby on Rails
20230610120000_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :name
    end
  end
end
This migration adds an email column to users and runs after the previous one because of its later timestamp.
Ruby on Rails
20230611130000_add_email_to_users.rb
class AddEmailToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :email, :string
  end
end
Sample Program

This example shows creating a books table with title and author columns. Rails uses the migration's timestamp version to track it.

Ruby on Rails
# Run in terminal:
# rails generate migration CreateBooks title:string author:string
# rails db:migrate

# Migration file example:
class CreateBooks < ActiveRecord::Migration[7.0]
  def change
    create_table :books do |t|
      t.string :title
      t.string :author
    end
  end
end

# After running rails db:migrate, Rails records the migration version in schema_migrations table.
OutputSuccess
Important Notes

Always keep migrations in order by timestamp to avoid conflicts.

Never edit old migrations after they have been run in production; create new migrations instead.

Summary

Migrations version the database to track changes over time.

This helps Rails know which changes are applied and which are pending.

Versioning prevents confusion and keeps database structure consistent.