Add Not null constraint after Rails

I noticed that I forgot to put a Not null constraint in the DB column. It's not good to modify the original migration file Also, create a new migration file with a Not null constraint.

rails g migration ChangeCloumnsNotnullAddUsers

Create migration file

There seem to be two ways!

change_column method

db/migrate/***_change_columns_add_notnull_on_users.rb


class ChangeColumnsAddNotnullOnUsers < ActiveRecord::Migration[5.2]
  def change
    change_column :users, :name, :string, null: false
    change_column :users, :email, :string, null: false
    change_column :users, :password, :string, null: false
  end
end

false → Add Not Null constraint`` true → Not null constraintnot

change_column :table name, :Column name, :Data type, null: false or true

Is it common to use the change_column method ...!

change_column_null

db/migrate/***_change_columns_add_notnull_on_users.rb


class ChangeColumnsAddNotnullOnUsers < ActiveRecord::Migration[5.2]
  def change
    change_column_null :users, :name, false
    change_column_null :users, :email, false
    change_column_null :users, :password, :string, false
  end
end

false → Add Not Null constraint`` true → Not null constraintnot

change_column_null :table name, :Column name, false or true

This one has a small amount of description and feels intuitive!

There seems to be a change_column_default method, but let's investigate it later.

Reference article

Rails Guide (https://railsguides.jp/active_record_migrations.html) https://qiita.com/MOssan-32/items/89afc9e4375215f8b5d2 https://qiita.com/akinov/items/852fe789fe98a44350a9

Recommended Posts

Add Not null constraint after Rails
Rails "Not Null Constraint" and "Validation (presence: true)" Note
[Rails] [Memo] When to add = to <%%> and when not
Add binding.pry (rails)
[Ruby on Rails] Add a column with a foreign key constraint
Difference between Not Null constraint and model validation (presence: true)
java.util.Optional class and null and not null
[Rails] Add / Remove Forms (cocoon)
[Rails] Add column to devise
[Rails] fields_for is not displayed