You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.adoc
+19Lines changed: 19 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -1026,6 +1026,25 @@ end
1026
1026
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.
1027
1027
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.
1028
1028
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`
0 commit comments