0
0
RailsHow-ToBeginner · 3 min read

How to Create Migration in Rails: Step-by-Step Guide

To create a migration in Rails, use the rails generate migration MigrationName command in your terminal. This creates a migration file where you define changes to your database schema, such as adding or removing tables or columns.
📐

Syntax

The basic syntax to create a migration in Rails is:

rails generate migration MigrationName [field:type field:type ...]

Here, MigrationName is a descriptive name for the change, and optional field:type pairs define columns to add or modify.

bash
rails generate migration AddTitleToPosts title:string
💻

Example

This example creates a migration to add a title column of type string to the posts table.

After running the command, edit the generated migration file if needed, then run rails db:migrate to apply changes.

bash
rails generate migration AddTitleToPosts title:string

# Migration file generated (timestamp_add_title_to_posts.rb):
# class AddTitleToPosts < ActiveRecord::Migration[7.0]
#   def change
#     add_column :posts, :title, :string
#   end
# end

rails db:migrate
Output
== 20240601000000 AddTitleToPosts: migrating =============================== -- add_column(:posts, :title, :string) -> 0.0012s == 20240601000000 AddTitleToPosts: migrated (0.0013s) ==============================
⚠️

Common Pitfalls

  • Using vague migration names like CreateTable instead of descriptive names like CreateUsersTable.
  • Forgetting to run rails db:migrate after creating the migration.
  • Editing migration files after they have been run without rolling back first.
  • Not specifying the correct data types for fields.
bash
### Wrong way:
rails generate migration CreateTable

### Right way:
rails generate migration CreateUsersTable name:string email:string
📊

Quick Reference

Here is a quick reference for common migration commands:

CommandDescription
rails generate migration MigrationNameCreates a new migration file
rails db:migrateRuns pending migrations to update the database
rails db:rollbackReverts the last migration
rails generate migration AddFieldToTable field:typeAdds a new column to a table
rails generate migration RemoveFieldFromTable field:typeRemoves a column from a table

Key Takeaways

Use rails generate migration MigrationName to create migration files.
Name migrations clearly to describe the database change.
Always run rails db:migrate to apply migrations.
Avoid editing migrations after running them without rollback.
Specify correct field types when adding or modifying columns.