How to change a nullable column to not nullable in a Rails migration? How to change a nullable column to not nullable in a Rails migration? ruby-on-rails ruby-on-rails

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 existMyModel.where(date_column: nil).update_all(date_column: Time.now)# Change the column to not allow nullchange_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


Rails 4 (other Rails 4 answers have problems):

def change  change_column_null(:users, :admin, false, <put a default value here> )  # change_column(:users, :admin, :string, :default => "")end

Changing a column with NULL values in it to not allow NULL will cause problems. This is exactly the type of code that will work fine in your development setup and then crash when you try to deploy it to your LIVE production. You should first change NULL values to something valid and then disallow NULLs. The 4th value in change_column_null does exactly that. See documentation for more details.

Also, I generally prefer to set a default value for the field so I won't need to specify the field's value every time I create a new object. I included the commented out code to do that as well.