Database migrations and schema management

Sarah Mitchell Feb 2026
2 tabs
# Create table migration
class CreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      t.string :email, null: false, index: { unique: true }
      t.string :name, null: false
      t.string :password_digest
      t.string :role, default: 'user'
      t.integer :posts_count, default: 0
      t.timestamp :last_login_at
      t.timestamps
    end

    add_index :users, :email
    add_index :users, :role
  end
end

# Add column migration
class AddAvatarToUsers < ActiveRecord::Migration[7.0]
  def change
    add_column :users, :avatar_url, :string
    add_column :users, :bio, :text
  end
end

# Remove column
class RemoveAvatarFromUsers < ActiveRecord::Migration[7.0]
  def change
    remove_column :users, :avatar_url, :string
  end
end

# Rename column
class RenameUserNameToFullName < ActiveRecord::Migration[7.0]
  def change
    rename_column :users, :name, :full_name
  end
end

# Change column type
class ChangeUserBioToText < ActiveRecord::Migration[7.0]
  def change
    change_column :users, :bio, :text
  end
end

# Add foreign key
class AddUserIdToPosts < ActiveRecord::Migration[7.0]
  def change
    add_reference :posts, :user, null: false, foreign_key: true, index: true
  end
end
2 files · ruby Explain with highlit

Rails migrations evolve database schema over time. I use change method for reversible migrations. Migrations create tables, add/remove columns, add indices. up and down methods provide explicit control. Irreversible migrations like data transformations need manual down. Database constraints—foreign keys, uniqueness, not null—ensure integrity. Indices speed queries—I add them to foreign keys and frequently queried columns. migrate:rollback undoes migrations. db:migrate:status shows applied migrations. Migrations are version-controlled, enabling team coordination. I keep migrations small and focused. Understanding SQL helps write efficient schema changes. Proper indexing dramatically improves production query performance.