Introduction
Migrations keep track of changes to the database so Rails knows what has been done and what still needs to be done.
Migrations keep track of changes to the database so Rails knows what has been done and what still needs to be done.
class AddAgeToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :age, :integer end end
20230610120000_create_users.rb class CreateUsers < ActiveRecord::Migration[7.0] def change create_table :users do |t| t.string :name end end end
20230611130000_add_email_to_users.rb class AddEmailToUsers < ActiveRecord::Migration[7.0] def change add_column :users, :email, :string end end
This example shows creating a books table with title and author columns. Rails uses the migration's timestamp version to track it.
# 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.
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.
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.
20240612123456_create_users.rb -> Option C20240601010101_create_users.rb20240602020202_add_email_to_users.rbrails db:migrate again without new migrations?rails db:migrate?20240612120000_add_age_to_users.rb and Developer B creates 20240612120000_add_status_to_users.rb. What issue arises and how should it be resolved?Pass the test and this pattern moves unknown