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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With