Rails Migration Stub Builder

Generate a Ruby on Rails migration file for common schema changes

Creates a Ruby on Rails ActiveRecord migration stub for create_table, add_column, add_index, or add_foreign_key, with a reversible change method, correct column types, and a timestamped filename suggestion.

What Rails version does the output target?

The migration class inherits from ActiveRecord::Migration[7.1], which works on Rails 7.x. Change the bracketed version to match your application if it differs.

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: true over a bare add_column for associations — it creates the column, the index, and the constraint in one reversible step.
  • Add null: false and default: options inside the column definitions where a value is required; the builder leaves room for them.
  • Run rails db:migrate to apply and rails db:rollback to undo. Because the output uses change, both directions work without extra code.