Skip to content

Commit cd6da97

Browse files
authored
Merge pull request #275 from tejasbubane/three-state-boolean
Add three-state boolean problem
2 parents 028c430 + b329f73 commit cd6da97

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

README.adoc

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,6 +1026,25 @@ end
10261026
While enforcing table defaults only in Rails is suggested by many Rails developers, it's an extremely brittle approach that leaves your data vulnerable to many application bugs.
10271027
And you'll have to consider the fact that most non-trivial apps share a database with other applications, so imposing data integrity from the Rails app is impossible.
10281028

1029+
=== 3-state Boolean [[three-state-boolean]]
1030+
1031+
With SQL databases, if a boolean column is not given a default value, it will have three possible values: `true`, `false` and `NULL`.
1032+
Boolean operators [work in unexpected ways](https://en.wikipedia.org/wiki/Three-valued_logic) with `NULL`.
1033+
1034+
For example in SQL queries, `true AND NULL` is `NULL` (not false), `true AND NULL OR false` is `NULL` (not false). This can make SQL queries return unexpected results.
1035+
1036+
To avoid such situations, boolean columns should always have a default value and a `NOT NULL` constraint.
1037+
1038+
[source,ruby]
1039+
----
1040+
# bad - boolean without a default value
1041+
add_column :users, :active, :boolean
1042+
1043+
# good - boolean with a default value (`false` or `true`) and with restricted `NULL`
1044+
add_column :users, :active, :boolean, default: true, null: false
1045+
add_column :users, :admin, :boolean, default: false, null: false
1046+
----
1047+
10291048
=== Foreign Key Constraints [[foreign-key-constraints]]
10301049

10311050
Enforce foreign-key constraints. As of Rails 4.2, Active Record supports foreign key constraints natively.

0 commit comments

Comments
 (0)