enums - Rails 4 migration to change columns data type from string to integer and back preserving data (postgres) -
i need convert string
fields integer
, use enum
instead. best way without losing data?
this current migration:
class createsystems < activerecord::migration def change create_table :systems |t| t.string :operation t.string :status t.timestamps null: false end end end
then change type of fields so:
class changecolumnsforsystems < activerecord::migration def change change_column :systems, :operation, :integer change_column :systems, :status, :integer end end
and update model file.
/app/models/system.rb
... enum operation { start: 0, stop: 1 } enum status { init: 0, working: 1, complete: 2 } ...
how can update old data?
after research found proper solution.
class changecolumnsforsystems < activerecord::migration def change change_column :systems, :operation, "integer using (case operation when 'start' '0'::integer else '1'::integer end)", null: false change_column :systems, :status, "integer using (case status when 'init' '0'::integer when 'working' '1'::integer else '2'::integer end)", null: false end end
update: in cases have remove default value prior changing type. here version rollback.
class changecolumnsforsystems < activerecord::migration def change_column_default :systems, :status, nil change_column :systems, :operation, "integer using (case operation when 'start' '0'::integer else '1'::integer end)", null: false change_column :systems, :status, "integer using (case status when 'init' '0'::integer when 'working' '1'::integer else '2'::integer end)", null: false, default: 0 end def down change_column_default :systems, :status, nil change_column :systems, :operation, "varchar using (case operation when '0' 'start'::varchar else 'stop'::varchar end)", null: false change_column :systems, :status, "varchar using (case status when '0' 'init'::varchar when '1' 'working'::varchar else 'complete'::varchar end)", null: false, default: 'init' end end
Comments
Post a Comment