Migrations help you change your database structure safely and easily. They keep track of changes so your app can grow without losing data.
0
0
Creating migrations in Ruby on Rails
Introduction
When you want to add a new table to your database.
When you need to add or remove columns from an existing table.
When you want to rename or change the type of a column.
When you want to delete a table you no longer need.
When you want to share database changes with your team.
Syntax
Ruby on Rails
rails generate migration MigrationName [field:type field:type ...]
MigrationName should describe the change, like AddEmailToUsers or CreateProducts.
You can add fields with their types right in the command to create columns.
Examples
This creates a migration to make a users table with name and age columns.
Ruby on Rails
rails generate migration CreateUsers name:string age:integer
This adds an email column to the existing users table.
Ruby on Rails
rails generate migration AddEmailToUsers email:string
This removes the age column from the users table.
Ruby on Rails
rails generate migration RemoveAgeFromUsers age:integer
Sample Program
This example creates a migration file to add a books table with title, author, and published_year columns. Running rake db:migrate applies the change to the database.
Ruby on Rails
rails generate migration CreateBooks title:string author:string published_year:integer
# Then run:
rake db:migrateOutputSuccess
Important Notes
Always write clear migration names to understand what changes they make.
Run rake db:migrate after creating migrations to apply changes.
You can rollback migrations if needed using rake db:rollback.
Summary
Migrations let you change your database structure step-by-step.
Use rails generate migration with a descriptive name and optional fields.
Run rake db:migrate to apply your migration changes.