【问题标题】:heroku: PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: “”heroku:PG :: InvalidTextRepresentation:错误:整数的无效输入语法:“”
【发布时间】:2016-10-12 13:40:42
【问题描述】:

我的事件模型上有一个货币(ccy)列,它目前是一个字符串,我想将其更改为整数。

虽然它适用于我的本地环境,但当我尝试heroku run rake db:migrate 到heroku 时显示以下错误。

rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: ""
: ALTER TABLE "events" ALTER COLUMN "ccy" TYPE integer USING CAST(ccy AS integer)

迁移文件如下。

class ChangeCcyToEvents < ActiveRecord::Migration
  def change
    change_column :events, :ccy, 'integer USING CAST(ccy AS integer)'
  end
end

我发现了类似的问题PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "M",所以我将迁移文件更改如下。但结果是一样的。

class ChangeCcyToEvents < ActiveRecord::Migration
  def change
    Event.where(ccy: '').update_all(ccy: '')
    change_column :events, :ccy, 'integer USING CAST(ccy AS integer)'
  end
end

到目前为止,所有ccy 列中都没有值。

如果您能给我任何建议,我们将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 heroku


    【解决方案1】:

    您的迁移正在尝试将 "" 转换为整数,postgres 对此表示不满(它应该这样做,因为它不是有效的转换)。

    您应该在更改列类型之前针对无效案例更新您的内容:

    class ChangeCcyToEvents < ActiveRecord::Migration
      def up
        Event.where("ccy IS NULL OR ccy = ''").update_all({ccy: '0'})
        change_column :events, :ccy, 'integer USING CAST(ccy AS integer)'
      end
    
      def down
        raise ActiveRecord::IrreversibleMigration
      end
    end
    

    也许在开发(本地主机)中没有抱怨,因为您使用的 postgreSQL 版本与 Heroku 不同。

    下次,尝试在此类列的迁移中使用default values

    【讨论】:

    • 你不能像ruby != javascript那样使用return,它应该会引发错误LocalJumpError: unexpected return。我想你的意思是next
    • @Зелёный 你是对的!我已将其更改为 next 命令。
    • 也适用于update_all 方法。
    • 最后,change_column方法是不可逆的
    • 感谢您的回答和评论,@Wikiti 和 @Зелёный。尽管我尝试了@Wikiti 回答的迁移文件,但出现了以下错误。StandardError: An error has occurred, this and all later migrations canceled: uninitialized constant ChangeCcyToEvents::Events 在中间显示错误NameError: uninitialized constant ChangeCcyToEvents::Events。如果您能给我任何建议,我们将不胜感激。
    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2012-12-21
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多