Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast old string values to datetime with migration in Rails PostgreSQL

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?

like image 444
Burak Özmen Avatar asked May 02 '16 11:05

Burak Özmen


1 Answers

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)'
like image 191
Jaques Dias Avatar answered Sep 21 '22 22:09

Jaques Dias