【问题标题】:ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR: column "completed_at" cannot be cast automatically to type timestamp without time zoneActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR: column \"completed_at\" 不能自动转换为类型 timestamp without time zone
【发布时间】:2022-09-25 09:35:30
【问题描述】:

我最初创建了一个 Task 模型,包括一个设置为 time 类型的 completed_at 字段,并进行了以下迁移:

class CreateTasks < ActiveRecord::Migration[7.0]
  def change
    create_table :tasks do |t|
      ...
      t.time :completed_at
      ...

      t.timestamps
    end
  end
end

随着项目的发展,我将completed_at 字段转换为timestamp 列,并进行了以下迁移:

class ChangeCompletedAtToBeTimestampInTasks < ActiveRecord::Migration[7.0]
  def change
    change_column :tasks, :completed_at, :timestamp
  end
end

该应用程序在本地运行良好,使用 SQLite3,但是当我尝试使用 PostgreSQL 为 Heroku 创建构建时,使用 heroku run rails db:migrate --app my_app_name 命令,我遇到了以下错误:

INFO -- : Migrating to ChangeCompletedAtToBeTimestampInTasks (20220713141025)
== 20220713141025 ChangeCompletedAtToBeTimestampInTasks: migrating ============
-- change_column(:tasks, :completed_at, :timestamp)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DatatypeMismatch: ERROR:  column \"completed_at\" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify \"USING completed_at::timestamp without time zone\".

加:

Caused by:
ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR:  column \"completed_at\" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify \"USING completed_at::timestamp without time zone\".

和:

Caused by:
PG::DatatypeMismatch: ERROR:  column \"completed_at\" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify \"USING completed_at::timestamp without time zone\".

this 11-year-old thread 的启发,我尝试通过添加without time zone 选项来修改将completed_at 列的类型不时更改为时间戳的迁移,但它并没有解决问题:

class ChangeCompletedAtToBeTimestampInTasks < ActiveRecord::Migration[7.0]
  def change
    change_column :tasks, :completed_at, :timestamp without time zone
  end
end

值得一提:

  1. 我不确定解决问题是否真的需要将timestamp 列设置为with time zonewithout time zone
  2. 我无法在线找到说明如何在 Rails 迁移中应用 without time zone 选项的文档,因此上面的代码可能不正确。

    关于如何解决这个问题并使构建通过的任何想法?

  • 您是否有任何数据要保留在 Heroku 的 completed_at 列中?
  • 否:该应用程序目前仅用于开发。我为解决此问题所做的是删除ChangeCompletedAtToBeTimestampInTasks 迁移并更新CreateTasks,以便completed_at 从一开始就是timestamp,然后我用种子重置数据库。
  • 如果您不关心数据,那是最简单的事情。接下来你应该在你的开发环境中安装 PostgreSQL,使用 SQLite 开发和部署在 PostgreSQL 上会导致各种问题。
  • 同意并完成:PostgreSQL 现在在所有三个环境中都实现了。谢谢你的帮助。

标签: ruby-on-rails postgresql heroku


【解决方案1】:

转到 pgadmin 并尝试这个对我有用的查询。

*ALTER TABLE shop_orders ALTER COLUMN 约会日期时间 TYPE TIMESTAMP USING 约会日期时间::TIMESTAMP;

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-19
    • 2012-04-04
    • 2021-11-12
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-10-26
    相关资源
    最近更新 更多