0
0
RailsHow-ToBeginner · 3 min read

How to Run Migration in Rails: Simple Steps to Update Your Database

To run a migration in Rails, use the rails db:migrate command in your terminal. This applies any pending database changes defined in your migration files to keep your database schema up to date.
📐

Syntax

The basic command to run migrations in Rails is rails db:migrate. This command looks for migration files in the db/migrate folder and applies any new changes to your database schema.

Additional useful commands include:

  • rails db:rollback - Reverts the last migration.
  • rails db:migrate:status - Shows which migrations have been run.
bash
rails db:migrate
💻

Example

This example shows how to create a migration to add a name column to a users table and then run the migration.

bash
rails generate migration AddNameToUsers name:string
rails db:migrate
Output
== AddNameToUsers: migrating =============================================== -- add_column(:users, :name, :string) -> 0.0012s == AddNameToUsers: migrated (0.0013s) ======================================
⚠️

Common Pitfalls

Common mistakes when running migrations include:

  • Not running rails db:migrate after creating migration files, so changes are not applied.
  • Running migrations in the wrong environment (e.g., development instead of production).
  • Editing migration files after they have been run, which can cause inconsistencies.
  • Forgetting to check migration status with rails db:migrate:status.
bash
## Wrong way: Editing a migration after running it
# This can cause errors or inconsistent schema

# Right way: Create a new migration to change schema
rails generate migration ChangeColumnInUsers
rails db:migrate
📊

Quick Reference

Here is a quick summary of useful migration commands:

CommandDescription
rails db:migrateRun all pending migrations
rails db:rollbackUndo the last migration
rails db:migrate:statusShow migration status
rails generate migration NAMECreate a new migration file

Key Takeaways

Run migrations with rails db:migrate to update your database schema.
Always create new migrations for changes instead of editing old ones.
Use rails db:migrate:status to check which migrations have run.
Rollback migrations safely with rails db:rollback if needed.
Ensure you run migrations in the correct environment.