41
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

change_column で 型を integer や boolean に変更すると失敗する問題の解決方法

Last updated at Posted at 2015-02-06

はじめに

change_column で string 型 だったフィールドを boolean に変更しようとしたら、失敗しました。Specify a USING expression to perform the conversion. と言われました。

[~/RubymineProjects/drwallet]$ rake db:migrate
==  ChangeColumnsToCreditCards: migrating =====================================
-- change_column(:credit_cards, :etc_issuance, :boolean)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::Error: ERROR:  column "etc_issuance" cannot be cast automatically to type boolean
HINT:  Specify a USING expression to perform the conversion.
: ALTER TABLE "credit_cards" ALTER COLUMN "etc_issuance" TYPE boolean/Users/gam0022/RubymineProjects/drwallet/db/migrate/20150206071431_change_columns_to_credit_cards.rb:3:in `change'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

解決方法

検索したらありました。

変更後の型を、通常であれば :integer とするところを、'integer USING CAST(column_name AS integer)'のようにすれば良いみたいです。

:boolean の場合でも同様の方法で解決できます。

migration.rb
-change_column :table_name, :column_name, :integer
+change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

補足

string から boolean にするときなどは、'true' や 'false' 以外のデータが入っていると上の方法でも失敗するので、全てのデータを 'false' などに置き換えて下さい。

41
31
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?