Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Ruby on Rails - Migrations in Rails

Introduction

Migrations are a feature of Rails that allow you to evolve your database schema over time in a consistent and easy way. They are a key part of Rails' infrastructure and help manage database changes in a version-controlled manner. This guide will cover the basics of creating and running migrations in Rails.

Key Points:

  • Migrations allow you to change your database schema over time.
  • They provide a way to version control your database changes.
  • This guide covers creating, running, and managing migrations in Rails.

Creating a Migration

To create a migration, use the Rails generator command:

# Generate a migration to create a table
rails generate migration CreateArticles title:string body:text

# This will create a migration file in db/migrate/ with the following content:
class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end
                

This migration defines a new table called articles with title and body columns, as well as the standard created_at and updated_at timestamp columns.

Running Migrations

To run the migrations and apply the changes to your database, use the following command:

# Run all pending migrations
rails db:migrate
                

This command will apply all pending migrations in the db/migrate/ directory to your database.

Modifying Existing Tables

Migrations can also be used to modify existing tables. Here is an example of adding a new column to an existing table:

# Generate a migration to add a column
rails generate migration AddPublishedAtToArticles published_at:datetime

# This will create a migration file in db/migrate/ with the following content:
class AddPublishedAtToArticles < ActiveRecord::Migration[6.0]
  def change
    add_column :articles, :published_at, :datetime
  end
end

# Run the migration to apply the changes
rails db:migrate
                

Rolling Back Migrations

If you need to undo a migration, you can roll it back using the following command:

# Roll back the last migration
rails db:rollback

# Roll back multiple migrations (replace 3 with the number of steps)
rails db:rollback STEP=3
                

This command will reverse the changes made by the last migration (or multiple migrations, if specified).

Migrations for Complex Changes

For more complex changes, you can use the up and down methods to define the actions for applying and rolling back the migration:

# Generate a migration for complex changes
rails generate migration RenameTitleToNameInArticles

# This will create a migration file in db/migrate/ with the following content:
class RenameTitleToNameInArticles < ActiveRecord::Migration[6.0]
  def up
    rename_column :articles, :title, :name
  end

  def down
    rename_column :articles, :name, :title
  end
end

# Run the migration to apply the changes
rails db:migrate
                

Data Migrations

Migrations can also be used to change data in the database. Here is an example of updating existing records:

# Generate a data migration
rails generate migration UpdateArticleTitles

# This will create a migration file in db/migrate/ with the following content:
class UpdateArticleTitles < ActiveRecord::Migration[6.0]
  def up
    Article.where(title: nil).update_all(title: "Untitled")
  end

  def down
    # No need to revert data changes in this case
  end
end

# Run the migration to apply the changes
rails db:migrate
                

Best Practices

Here are some best practices for working with migrations in Rails:

  • Keep migrations atomic: Each migration should make a single, small change.
  • Write reversible migrations: Ensure that migrations can be rolled back if needed.
  • Test migrations: Run migrations in a development environment before applying them to production.
  • Use descriptive names: Name migrations clearly to indicate their purpose.

Conclusion

Migrations are a powerful tool in Rails for managing changes to your database schema over time. By understanding how to create, run, and manage migrations, you can ensure that your database evolves in a controlled and consistent manner.