If I use a migration to update a database, and I add an integer field like this:
t.integer :foo :default => 0, :null => false
What is the default state of existing and new records in the database? I hoping the answer is: - Both will read back foo as 0.
Is default => 0 necessary, if I have :null => false?
Just trying to understand the difference between the two...
The null: false parameter means this column does not allow NULL values. The default: false tells us this column will default to false whenever a value isn't specified. This is nice because we can guarantee this field will always be either true or false now. It can't be null because the database prevents it.
Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.
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.
:null => false
tells your database not to accept NULL
values.
:default => 0
does two things:
NULL
or nothing is specified in a query.Point 2 makes sure that when you save your new object, you actually have a valid value in place.
To answer your question: If you don't want NULL
values in your database, set :null => false
, otherwise just use the :default
parameter. Mind you, '0' and NULL
are not the same things.
Not having NULL
values might be important for indexing purposes or if you need to provide direct database access to a third party.
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