将“deleted_at”时间列转换为日期时间列的Rails迁移失败。关于如何解决这个问题的任何想法?如果相关的话,这是Postgres的全新安装。
-- change_column(:products, :deleted_at, :datetime)
PGError: ERROR: column "deleted_at" cannot be cast to type timestamp without time zone
: ALTER TABLE "products" ALTER COLUMN "deleted_at" TYPE timestamp
答案 0 :(得分:10)
在Rails中,这看起来像
class ChangeStatusUpdatedAtToDateTime < ActiveRecord::Migration
def up
remove_column :bookings, :status_updated_at
add_column :bookings, :status_updated_at, :datetime
end
def down
remove_column :bookings, :status_updated_at
add_column :bookings, :status_updated_at, :time
end
end
答案 1 :(得分:7)
您无法在时间戳(“datetime”)之间更改字段的类型,因为无法转换值 - 数据库不会知道日期。
但是,您可以删除并重新创建列:
ALTER TABLE products DROP COLUMN deleted_at;
ALTER TABLE products ADD COLUMN deleted_at timestamp;
或者如果此字段设置为NOT NULL,则应该执行:
ALTER TABLE products ADD COLUMN deleted_at timestamp NOT NULL;
但是如果你像Sean一样坚持在这个表中保留假值,你可以使用ALTER ... TYPE ...这样使用:
ALTER TABLE products ALTER COLUMN deleted_at TYPE timestamp USING
CASE WHEN deleted_at IS NOT NULL THEN timestamp '1970-01-01 00:00:00' END;
-- Or:
ALTER TABLE products ALTER COLUMN deleted_at
TYPE timestamp USING date '1970-01-01' + deleted_at;