1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】カラムの型を間違えた時の修正法【マイグレーション関連】

Posted at

データベースに登録する型を間違えた時の修正方法を
ご紹介します。

スクリーンショット 2026-02-01 19.59.30.png

今回は上記のカラム型の中の

「gender」性別のところを

boolean型からstring型に変更してみます。

前提知識 カラムの型の種類

rails_columns.png

前提知識2 マイグレーションとはなんぞや

rails_migration_guide.png

カラムの型の変更方法

①コンソールにてコマンドを打ちます。

$ rails g migration [マイグレーションファイル名]

$ rails g migration ChangeStatusTypeForTasks
※マイグレーションファイル名は見る人がわかりやすいもの推奨です☺️

するとこんなファイルができます。
Image from Gyazo

開くとこんな感じ。

class ChangeStatusTypeForTasks < ActiveRecord::Migration[7.2]
  def change
  end
end

②ここに変更したい内容を入れていきます。

class ChangeStatusTypeForTasks < ActiveRecord::Migration[7.2]
  def change
    # カラムの型を変更します。ここでは status カラムを文字列型から整数型に変更しています。
    change_column :tasks, :status, :integer

    # もしデフォルト値や null 制約も設定したい場合は、以下のように追加します。
    # change_column :tasks, :status, :integer, default: 0, null: false
  end
end

③出来上がったら変更!(マイグレーション)

rails db:migrate

④できているか確認しよう!

スクリーンショット 2026-02-01 23.07.57.png

db/migrate/schema.rbの中身を確認して
変更されていればOKです! 

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?