I had a couple of date fields in a database table, however they are firstly initiated as string, not datetime. Therefore, I wanted to change those value types to datetype with a migration,
class ChangeDateColumnsToDateTime < ActiveRecord::Migration
def change
change_column :users, :flight_date_departure, :datetime
change_column :users, :flight_date, :datetime
change_column :users, :appointment_date, :datetime
end
end
however it can not cast old string values to datetimes that exists in database currently, saying that PG::DatatypeMismatch: ERROR: column "flight_date_departure" cannot be cast automatically to type timestamp without time zone. HINT: You might need to specify "USING flight_date_departure::timestamp without time zone". We've done it without problem in a SQLite database, however there is this problem for PostgreSQL. How can I modify my migration so that I do not lose old values and properly convert them to datetime?
I've tried the way bellow and it worked like a charm:
change_column :table_name, :column_name, 'timestamp USING CAST(column_name AS timestamp)'
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