Rails Migrations CLI

Basic migration syntax:

rails generate migration AddPartNumberToProducts

It will generate a named migration:

class AddPartNumberToProducts < ActiveRecord::Migration
  def change
  end
end

Below is the naming convention for generating code for migrations automatically.

Creating a Migration

AddXXXToYYY <fields>

rails generate migration AddPartNumberToProducts part_number:string
class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
  end
end

RemoveXXXFromYYY <fields>

rails generate migration RemovePartNumberFromProducts part_number:string
class RemovePartNumberFromProducts < ActiveRecord::Migration
  def change
    remove_column :products, :part_number, :string
  end
end

CreateXXX <fields>

rails generate migration CreateProducts name:string part_number:string
class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.string :part_number
    end
  end
end

AddXXXRefToYYY <fields>

rails generate migration AddUserRefToProducts user:references
class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :user, index: true
  end
end

CreateJoinTableXXXYYY <xxx> <yyy>

rails g migration CreateJoinTableCustomerProduct customer product
class CreateJoinTableCustomerProduct < ActiveRecord::Migration
  def change
    create_join_table :customers, :products do |t|
      # t.index [:customer_id, :product_id]
      # t.index [:product_id, :customer_id]
    end
  end
end

Notes

Based on http://guides.rubyonrails.org/migrations.html