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?

More than 3 years have passed since last update.

カラムのdefault制約をマイグレーションで変更する

Posted at

emailカラムのDEFAULT制約を消す

schema.rb
create_table "users", force: :cascade do |t|
-  t.string "email", null: false, default: ""
+  t.string "email", null: false
end
class RemoveDefaultRestrictFromUsers < ActiveRecord::Migration[6.0]
  def change
    change_column_default :users, :email, from: "", to: nil
  end
end

補足:from-toを省略した change_column_default :users, :email, nil の書き方でもdefault制約を消すことはできたのですが、db:rollbackが失敗します。(元の値が分からなくなるため)

adminカラムの初期値をtrueからfalseに変える

schema.rb
create_table "users", force: :cascade do |t|
-  t.string "admin", null: false, default: true
+  t.string "admin", null: false, default: false
end
class RemoveDefaultRestrictFromUsers < ActiveRecord::Migration[6.0]
  def change
    change_column_default :users, :admin, from: true, to: false
  end
end

Railsでカラムのデフォルト値を変更する方法 - Qiita にもあるように、up, downを記述することなくrollbackできる書き方なので便利です :yum:

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?