LoginSignup
60

More than 1 year has passed since last update.

Railsのmigrationで後からNULL制約を設定する

Last updated at Posted at 2018-12-07

NULL制約の追加には change_column_null を使います。
引数にはテーブル名、カラム名、null falseかtrueか、変更後のデフォルト値

class ChangePointColumnOnPost < ActiveRecord::Migration[5.2]
  def change
    change_column_null :posts, :point, false, 0
  end
end

これだとちょっと問題が…

ここで設定されるdefaultは現在nullのカラムを変更するためだけのもので、テーブルの制約にdefault値が設定されるわけではないので、nullでレコードの追加をしようとした際にコケてしまいます。
そのため別でデフォルト値の設定が必要になります。

NULL制約追加+デフォルト0を設定するコード
postsテーブルのpointカラムがNULL制約なし、デフォルトNULLになっているのを、NULL禁止、デフォルト0に変更するマイグレーションになります。

class ChangePointColumnOnPost < ActiveRecord::Migration[5.2]
  def change
    change_column_null :posts, :point, false, 0
    change_column_default :posts, :point, from: nil, to: 0
  end
end

※自ブログからの転載です
http://akinov.hatenablog.com/entry/2019/06/20/164836

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
60