50
42

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でNotNull制約を後からカラムに追加する方法2種類

Last updated at Posted at 2019-07-08

初投稿です!
Migrationファイル生成してNotNull制約を既存のカラムに追加する際、少し手間取ったのでメモ。

change_column_nullメソッドを使った場合

class ChangeColumnsAddNotnullOnTasks < ActiveRecord::Migration[5.2]
  def change
    change_column_null :tasks, :title, false
    change_column_null :tasks, :created_at, false
    change_column_null :tasks, :updated_at, false
  end
end

NotNull制約を付与する:false(change_column_nullメソッド)

change_column_null :テーブル名, :カラム名, false

NotNull制約を解除する:true(change_column_nullメソッド)

change_column_null :テーブル名, :カラム名, true

change_columnメソッドを使った場合の書き方

class ChangeColumnsAddNotnullOnTasks < ActiveRecord::Migration[5.2]
  def change
    change_column :tasks, :title, :string, null: false
    change_column :tasks, :created_at, :datetime, null: false
    change_column :tasks, :updated_at, :datetime, null: false
  end
end

NotNull制約を付与する:false(change_columnメソッド)

change_column :テーブル名, :カラム名, :データ型, null: false

NotNull制約を解除する:true(change_columnメソッド)

change_column :テーブル名, :カラム名, :データ型, null: true

Default値(初期値)を設定したい時は、default: をつける

class AddNotnullToDeadlineOnTasks < ActiveRecord::Migration[5.2]
  def change
    change_column :tasks, :deadline, :datetime, default: "", null: false
  end
end

マイグレーション実行時にエラーが起きてあたふたしたのですが、
change_column_nullの場合の書き方と、change_columnの書き方がまぜこぜになってしまったのが原因でした!

50
42
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
50
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?