Generate Rails migrations that automagically add your change

Rails’ generators can pump out code and save you from tedious work.

This command generates a person model with a name and age:

rails g model person name:string age:integer

When you generator a decimal field you can specify the precision — the total number of digits in the number, and the scale — the number of digits following the decimal point.

rails g model book price:decimal{5,2}:index

When you generate a migration, by following Rails’ migration name conventions, Rails will generate the fields. For example, this command generates the following migration:

rails g migration add_body_and_pid_to_people body:string:index pid:integer:uniq

class AddBodyAndPidToPersons < ActiveRecord::Migration
  def change
    add_column :persons, :body, :string
    add_index :persons, :body

    add_column :persons, :pid, :integer
    add_index :persons, :pid, :unique => true
  end
end

You should always check the generated migration though, it’s not perfect. The migration generated by this command should remove the index, along with the column.

rails g migration remove_body_from_people body:string:index

However, the generated migration does not remove the index.

class RemoveBodyFromPeople < ActiveRecord::Migration
  def up
    remove_column :people, :body
  end

  def down
    add_column :people, :body, :string
  end
end

Update: I fixed this issue Rails.