Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

はじめに

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)

解決方法

検索したらありました。

http://stackoverflow.com/questions/13170570/change-type-of-varchar-field-to-integer-cannot-be-cast-automatically-to-type-i

変更後の型を、通常であれば :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' などに置き換えて下さい。

gam0022
CGとWebに興味があります。 最近はレイマーチングが熱いです。
https://gam0022.net/
klab
モバイルオンラインゲーム、その他スマートフォン関連サービス、及びサーバーインフラ開発・運用
http://www.klab.com/jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした