Write a correct Rails migration the first time
ActiveRecord migrations are easy to get subtly wrong — a missing index, a non-reversible change, or the wrong column type that only surfaces on rollback. This builder generates a clean, reversible migration for the four operations you reach for most often, with the right helpers and a timestamped filename so it drops straight into db/migrate.
How it works
Pick one operation and the builder emits a change method using the matching ActiveRecord helper:
create table -> create_table :name do |t| ... t.timestamps end
add column -> add_column :table, :col, :type
add index -> add_index :table, [:cols], unique: ...
add foreign key -> add_reference :table, :ref, foreign_key: true
For create_table you list columns as name type; the builder writes each as t.type :name and appends t.timestamps so created_at and updated_at are populated automatically. Column types map to Rails primitives (string, text, integer, boolean, decimal, datetime, references). The class name is derived from the operation and table (for example CreateUsers), inherits from ActiveRecord::Migration[7.1], and everything lives inside the reversible change method.
Tips and notes
- The suggested filename uses a UTC timestamp prefix. Rails sorts and tracks migrations by that number, so keep it unique and never reuse one.
- Prefer
add_reference ... foreign_key: trueover a bareadd_columnfor associations — it creates the column, the index, and the constraint in one reversible step. - Add
null: falseanddefault:options inside the column definitions where a value is required; the builder leaves room for them. - Run
rails db:migrateto apply andrails db:rollbackto undo. Because the output useschange, both directions work without extra code.