How to change a nullable column to not nullable in a Rails migration?
If you do it in a migration then you could probably do it like this:
# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)
# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false
In Rails 4, this is a better (DRYer) solution:
change_column_null :my_models, :date_column, false
To ensure no records exist with NULL
values in that column, you can pass a fourth parameter, which is the default value to use for records with NULL
values:
change_column_null :my_models, :date_column, false, Time.now