DEV Community

Viral Patel
Viral Patel

Posted on • Originally published at viralpatel.blog on

Toggle NOT NULL constraint with Rails migration

Take advantage of change_column_null to add or remove NOT NULL constraint on a column. The null flag indicates whether the value can be NULL.

To add the constraint (says column cannot be NULL):

change_column_null :users, :name, false
Enter fullscreen mode Exit fullscreen mode

To remove the constraint (allows the column to be NULL):

change_column_null :users, :name, true
Enter fullscreen mode Exit fullscreen mode

The method accepts an optional fourth argument to replace existing +NULL+s with some other value. Use that one when enabling the constraint if needed, since otherwise, those rows would not be valid.

Note: Please note the fourth argument does not set a column’s default.

Top comments (1)

Collapse
 
saronyitbarek profile image
Saron

This was really helpful, thank you Viral!