4
4

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.

Railsのmigrationでデフォルト値にbooleanを設定する

Last updated at Posted at 2016-08-15

migrationファイルを作るコマンド

¥ bin/rails g migration add_default_to_event_hoge_flag

カラムのデフォルト値を変更する方法

class AddDefaultToEventHogeFlag < ActiveRecord::Migration
  def change
	change_column_default(:events, :hoge_flag, false)
  end
end

ずっとエラーに悩まされた。
PG::Error: ERROR: relation "event" does not exist

Railsのテーブル名は複数形であることを忘れておった。
Eventクラスからコピペしたからテーブル名は絶対に合ってると思ってしまった。

変更されたかチェックする

¥ bin/rails c
¥ Event.columns

2016/8/16日追記しました〜

rollbackを考慮する

以下を実行すると、一つ前のmigrationの状態まで戻ることが出来るが上の対応だけだとrollbackした時にエラーになる

¥ bin/rake db:rollback
==  AddDefaultToEventHogeFlag: reverting ====================================
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

ActiveRecord::IrreversibleMigration
ActiveRecord::IrreversibleMigration: ActiveRecord::IrreversibleMigration

Tasks: TOP => db:rollback
(See full trace by running task with --trace)

なので、updownを使って処理を書き直します

class AddDefaultToEventHogeFlag < ActiveRecord::Migration
  # db:migrateした時に実行される処理
  def up
    change_column_default(:events, :hoge_flag, false)
  end
  # db:rollbackした時に実行される処理
  def down
    change_column_default(:events, :hoge_flag, nil)
  end
end

これで上手くいくようになりました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?