I have a model with a column of type integer
which I want to convert to type string
. Now I'm looking for the best way to change the column type without losing the data. Is there a painless way to accomplish this?
If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again: rename_column :table_name, :old_column1, :new_column1 rename_column :table_name, :old_column2, :new_column2 ...
The migration that cannot be undone: Irreversible Migration.
A standard migration using the change_column method will convert integers to strings without any data loss. rake db:rollback will also do the reverse migration without error if required.
Here is the test migration I used to confirm this behaviour:
class ChangeAgeToString < ActiveRecord::Migration def self.up change_column :users, :age, :string end def self.down change_column :users, :age, :integer end end
for postgres in migration
change_column :table_name, :field,'boolean USING (CASE field WHEN \'your any string as true\' THEN \'t\'::boolean ELSE \'f\'::boolean END)'
and to any valid type similar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With