Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Migration, converting from string to enum

If I've got a production database that has "types" stored as string, but I want to convert that column to an integer for enum.

I've googled/SO'd, and I see that I can CAST, but not sure what that does exactly.

If it's not hard, I'd love ot use rails enum, but otherwise, maybe I should stick with my string schema...

Please advise!

like image 533
Kevin Brown Avatar asked Dec 25 '22 09:12

Kevin Brown


1 Answers

You can rename existing column, create a new one called "types" (integer), then write a script that stores appropriate integer value in the new column, and then drop the old column.

The migration will look like this:

class FixTypes < ActiveRecord::Migration
  def change
    rename_column :table_name, :types, :old_types
    add_column :table_name, :types, :integer
  end
end

Then write a script that sets the value of "types" based on "old_types":

Model.all.each do |entry|
  entry.types = %w(status1 status2 status3 status4).index(entry.old_types)
  entry.save!
end

And then drop the "old_types" column.

like image 197
amit_saxena Avatar answered Jan 04 '23 00:01

amit_saxena