【发布时间】:2016-08-27 03:29:13
【问题描述】:
我在数据库表中有几个日期字段,但是它们首先以字符串而不是日期时间的形式启动。因此,我想通过迁移将这些值类型更改为 datetype,
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
但是它不能将旧字符串值转换为当前存在于数据库中的日期时间,也就是说 PG::DatatypeMismatch: 错误:列“flight_date_departure”不能自动转换为没有时区的类型时间戳。提示:您可能需要指定“USING flight_date_departure::timestamp without time zone”。我们已经在 SQLite 数据库中完成了它,但 PostgreSQL 存在这个问题。如何修改我的迁移,以免丢失旧值并将它们正确转换为日期时间?
【问题讨论】:
-
解决方法: 添加新的
datatime列,写一个rake task将字符串值复制到数据时间列(可能您需要使用to_datetime将字符串转换为日期时间),删除旧字符串列,您可能需要将日期时间列重命名为flight_date_departure
标签: ruby-on-rails postgresql datetime