This is all assuming that the datatype of the column has an implicit conversion for any existing data. I've run into several situations where the existing data, let's say a String
can be implicitly converted into the new datatype, let's say Date
.
In this situation, it's helpful to know you can create migrations with data conversions. Personally, I like putting these in my model file, and then removing them after all database schemas have been migrated and are stable.
/app/models/table.rb
...
def string_to_date
update(new_date_field: date_field.to_date)
end
def date_to_string
update(old_date_field: date_field.to_s)
end
...
def up
# Add column to store converted data
add_column :table_name, :new_date_field, :date
# Update the all resources
Table.all.each(&:string_to_date)
# Remove old column
remove_column :table_name, :date_field
# Rename new column
rename_column :table_name, :new_date_field, :date_field
end
# Reversed steps does allow for migration rollback
def down
add_column :table_name, :old_date_field, :string
Table.all.each(&:date_to_string)
remove_column :table_name, :date_field
rename_column :table_name, :old_date_field, :date_field
end