3

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

You can't use return like that ruby != javascript , it should raise an error LocalJumpError: unexpected return. I think you mean next
@Зелёный You're right! I have changed it to a next command.
Also it is work for update_all method.
And last, the change_columnmethod is irreversible.
Thank you for your answer and comment, @Wikiti and @Зелёный. Although I tried the migration file which @Wikiti answered, the following error was appeared.StandardError: An error has occurred, this and all later migrations canceled: uninitialized constant ChangeCcyToEvents::Events At the middle of error NameError: uninitialized constant ChangeCcyToEvents::Events was displayed. It would be appreciated if you could give me any advice.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.