Reputation: 432
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?
Upvotes: 1
Views: 1110
Reputation: 1484
I think you will need some stuff in up
method within migration.
def up
add_column :table_name, :status2, :boolean
Loop on each element of model check for status and update status2
remove_column :table_name, :status
rename_column :table_name, :status2, :status
end
You can also go with case statement in update here It will help. You can put your query in migration as well something similar to here.
You can also do one more thing like :
1. Make migration to add new column.
2. Make rake task to populate data.
3. Make one more migration to delete old column and rename newly added column.
Update : For better understanding on migration do read this article.
Upvotes: 0
Reputation: 3775
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.
Upvotes: 1