Search code examples
ruby-on-railspostgresqldatabase-migration

Rails migration. Cast integer values into boolean with change_column


I'm using RoR5 with PostgreSQL. I have a table with a column status. Which is of a type integer and holds three values 0, 1, 2. Those values represent three statuses allowed, not_allowed and no_tests.

I'm gonna change the logic. I want to convert two statuses allowed and not_allowed into boolean. Then I'll create a separate column for the no_tests.

Right now I have this accordance: enum status: %i[allowed not_allowed no_tests].

How should I write a migration to have allowed as true and both not_allowed and no_tests as false in the changed column?


Solution

  • Actually this is two separate operations (change table structure, convert existing data), only one of would typically be done in a migration. If I were you I would first run a migration to add the new status column, and then do an update either in sql if you have easy access to the postgres console or at the rails console to recode the existing data in your new column. After you've recoded the data you can drop the old columns in another migration.