Skip to content
Advertisement

Writing a Rails migration to collapse booleans into an enum

I made a mistake when modeling my data and created a model with 4 booleans, only one of which are active at a time. I want to create a column of Postgres enum type, and then set the value based on which boolean flag was previously set.

I know I want to start with something like this:

My question is: What can I do where my TODO comments are? Previously I wrote a migration to go from an integer to a Postgres enum in my User model, and my change_column code looked like this:

I imagine that the code I’m trying to write is some variation of this with a flurry of if statements. Any input would be appreciated.

Advertisement

Answer

Although you have suggested the approach yourself in question, but here is the solution anyway.

Based on this article. You can try something like below:

I have not tried to run this code, you should correct any typos you may find(and comment here as well so i can update answer).

Please also read the article i have linked above for proper usage of postgres enums on models.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement