How to change the column type with Rails migrate

How to change the column type with a Rails migration. Lets find out how to do this common Rails task.

A common change that you will make to Rails projects is you start with a model having an attribute of one type and then you realise it needs to be another.

This might be something like thinking you should store an integer when it should actually be a string. New developers often think phone numbers should be stored as integers because they are numbers, but forget that integers can’t start with zero (and most phone numbers start with zero).

To kick things off we need to generate a new migration

  rails g migration change_phone_to_be_string_in_customers

What you call this migration will have no impact on what we need to do next, but future you and other developers will thank you for naming your migration appropriately.

If you open up the migration you should see something like this

  class ChangePhoneToBeStringInCustomers < ActiveRecord::Migration[5.0]
    def change
    end
  end

As you can see the change method is sitting empty. We need to manually add some code here.

The code we need to add takes the form of

  change_column :table_name, :column_name, :new_type

In our case it would be something like

  change_column :customers, :phone, :string

The completed file will look like this

class ChangePhoneToBeStringInCustomers < ActiveRecord::Migration[5.0]
  def change
    change_column :customers, :phone, :string
  end
end

Once you’ve saved the file you should be able to do a quick rake db:migrate and your database will update.

Recent posts View all

Slack

Integrating RSS feeds to Slack (including YouTube)

How to add an RSS feed to a Slack channel

Freelancing

Our Setup

Here is a writeup of the hardware and software we use on a daily basis