Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change column type to integer rails

I have run a migration when trying to change on heroku table column from string to integer: This is my migration:

class ChangePriceTypeInItems < ActiveRecord::Migration
  def change
    change_column :items, :price, :integer
  end
end

And this is my error: What do I do?

ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "price" cannot be cast automatically to type integer
HINT:  You might need to specify "USING price::integer".
: ALTER TABLE "items" ALTER COLUMN "price" TYPE integer
like image 229
user2950593 Avatar asked May 13 '26 20:05

user2950593


2 Answers

The other answers are correct, yet you can also use the :using keyword:

change_column :items, :price, :integer, using: 'price::integer'
like image 178
João Souza Avatar answered May 15 '26 09:05

João Souza


If you're sure the data in the string column can be converted to integer then go ahead with this change to your migration:

change_column :items, :price, 'integer USING CAST(price AS integer)'

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!