3-state Boolean field
I’ve been through a piece of code today that reminded me this specific case on Rails Migrations:
add_column :table_name, :column_name, :boolean
How does that look to you? Ok? Well, it seems ok, right? If that wasn’t a boolean
field, it would be just fine, although for boolean
fields, that’s not correct. This way we have 3 possible values for that field, true
, false
and nil
.
Avoiding the problem #
To avoid this, we must add the option null: false
, which will leave you with only the two possible values for booleans, true
and false
. Great, we have that fixed.
Wait, what? #
In case you have previous data on this table, your migration might not be able to successfully execute. The reason is that your database does not know what to put on that newly added column, for those previously entered rows. The default behaviour is to just add NULL
, although we just added a constraint nil: false
, which “blocks” the default behaviour.
How to fix problem 2 #
To fix this second problem is also pretty simple, we can add a default
option to add_column
method to orient our migration on what to do.
add_column :table_name, :column_name, :boolean, nil: false, default: false
You can pick whatever makes sense to your business needs, true
or false
.
Done, this way we have a safe migration adding a boolean column to a table.