SamuraiBlue
SamuraiBlue

Reputation: 861

heroku: PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: “”

I have a currency(ccy) column on my event model and it's currently a string, I'd like to change it to a integer.

Although it works on my local environment, the following error was displayed when I try heroku run rake db:migrate to 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)

The migration file as below.

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

I found the similar question PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "M", so I changed migration file as below. But the result is the same.

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

There is no value in all ccy column so far.

It would be appreciated if you could give me any advice.

Upvotes: 3

Views: 3095

Answers (1)

Wikiti
Wikiti

Reputation: 1636

Your migration is trying to convert a "" into an integer, which postgres complais about it (and it should, because it's not a valid conversion).

You should update your content for invalid cases before changing the column type:

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

Perhaps is not complaining in development (localhost) because you're using a different version of postgreSQL than Heroku.

Next time, try using default values in migrations for this kind of columns.

Upvotes: 4

Related Questions