Categories
Databases PostgreSQL Rails Ruby

Change column type from boolean to integer

Background

I had an ActiveRecord Class Message with a read column of type boolean. This column was used, you guessed it, to know if the message had been read by the recipient.

Initially this column was of type boolean because it was a simple true/false case but as I continued working on the project and extending the functionality of the Message class I had to introduce a state machine in order to take advantage of callbacks.

Since I was going to introduce more states and wanted to keep the column as slim as possible I decided to integers instead and declare the enum in the class.

Solution

See the gist on github.

Explanation

  • First we need to add the new state column of type integer.
  • Then we need to copy the data from the read column to the state column. We need to CAST read as integer so it doesn’t blow up.
  • To finish, we remove the read column.

Leave a Reply