Adding, Renaming, and Removing Columns in Rails Migrations

This post goes over the best practices when adding, renaming, and removing columns from a Rails application’s database. This is accomplished using Rails’ built-in generators to ensure following Rails best practices.

This guide assumes that the database and the table being used have already been created.

Add a column to an existing table

To add a new column to an existing table in a rails database, use the following sample generator.

To generate a new migration that adds a new column called breeds to an existing table called cats, the following rails command could be used:

rails generate migration AddBreedsToCats breed:string

Note the pluralizations when naming the migration, while the singular is used when specifying the column name and type at the end of the command.

The generated migration will look like the following:

1
2
3
4
5
class AddBreedsToCats < ActiveRecord::Migration
  def change
    add_column :cats, :breed, :string
  end
end

Adding multiple columns

Multiple columns can be added by specifying them in order when generating the migration:

rails g migration AddWeightAndCutenessToCats weight:integer 'cuteness:decimal{3,2}'

This will generate a migration that creates two columns:

  • weight: An integer column to track the cat’s weight
  • cuteness: An average of cuteness ratings submitted by users for the cat, can have values 0-9.99 with two places of precision (3 digits, 2 digits precision)

The generated migration will look like the following:

1
2
3
4
5
6
class AddWeightAndCutenessToCats < ActiveRecord::Migration
  def change
    add_column :cats, :weight, :integer
    add_column :cuteness, :decimal, :precision => 3, :scale => 2
  end
end

Renaming an existing column

To rename the column called breed in the cats table to breed_name, generate a migration

rails g migration RenameBreedToBreedNameInCats

Rails won’t recognize this and automatically create the migration — rename isn’t a word that it recognizes when generating migrations. Open the migration file that rails generated, and modify it to look like the following:

1
2
3
4
5
6
7
8
9
class RenameBreedToBreedNameInCats < ActiveRecord::Migration
  def up
    rename_column :cats, :breed, :breed_name
  end

  def down
    rename_column :cats, :breed_name, :breed
  end
end

Removing an existing column

To remove a column from the rails database, use the following generator:

rails g migration RemoveCutenessFromCats 'cuteness:decimal{3,2}'

It is important to specify any type options when generating a migration that removes a column from the database. This will ensure that the migration can be run in reverse, if needed.