カラムの型をstringからintegerやbigintに変更しようとしてエラーが出た時の話

カラムの型をstring型からbigint型に変更しようと思って以下のようにmigrationファイルを編集して

class ChangeColumnParentStringToBigint < ActiveRecord::Migration[5.2]
  def change
    change_column :categories, :parent_id, :bigint, null: true
  end
end

rails db:migrateしたところ...

-- change_column(:categories, :parent_id, :integer, {:nill=>true})
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DatatypeMismatch: ERROR:  column "parent_id" cannot be cast automatically to type integer
HINT:  You might need to specify "USING parent_id::integer".
: ALTER TABLE "categories" ALTER COLUMN "parent_id" TYPE integer

とエラー出てしまいます。 日本語に直すとこんな感じです

自動的に整数型にキャストすることはできません "USING parent_id :: integer"を指定する必要があります。

その後、Rollbackしたりして色々やって結構ハマったのでメモ

対応

変更後の型を:bigintと書くのではなく'bigint USING CAST(parent_id AS bigint)'とすることで解決しました

class ChangeColumnParentStringToBigint < ActiveRecord::Migration[5.2]
  def change
    change_column :categories, :parent_id, 'bigint USING CAST(parent_id AS bigint)'
  end
end

integerでも同じように解決できます。

参考

stackoverflow.com

qiita.com