Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: How do I add a not null constraint to an existing column using a migration?

People also ask

How do you add NOT NULL constraints in existing columns?

To add not null constraint to an existing column in MySQL, we will use the ALTER command. This is a type of validation to restrict the user from entering null values.

How do you add NOT NULL constraints to an existing table syntax?

The basic syntax of an ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows. ALTER TABLE table_name MODIFY column_name datatype NOT NULL; The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows.

Can a column defined with NOT NULL constraint?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

What is null false in rails migration?

According to the documentation one of these options is :null which allows or disallows NULL values in the column. So, in summary :null => false would mean "Do not allow NULL values in the new or update column".


You can also use change_column_null:

change_column_null :table_name, :column_name, false

For Rails 4+, nates' answer (using change_column_null) is better.

Pre-Rails 4, try change_column.


1) FIRST: Add column with default value

2) THEN: Remove default value

add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil

If you are using it on a new create migration script/schema here is how we can define it

class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
    t.string :name, null: false     # Notice here, NOT NULL definition
    t.string :email, null: false
    t.string :password, null: false
    t.integer :created_by
    t.integer :updated_by 

    t.datetime :created_at
    t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' }
   end
  end
end