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".
To check for status, run rails db:migrate:status . Then you'll have a good view of the migrations you want to remove. Then, run rails db:rollback to revert the changes one by one. After doing so, you can check the status again to be fully confident.
Here is the syntax for it. ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL; Replace table_name, col_name and data_type with table name, column name and data type respectively. Here's the SQL query to change amount column from NULL to NOT NULL.
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
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.
Create a migration that has a change_column
statement with a :default =>
value.
change_column :my_table, :my_column, :integer, :default => 0, :null => false
See: change_column
Depending on the database engine you may need to use change_column_null
Rails 4:
def change
change_column_null(:users, :admin, false )
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