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
+15-4Lines changed: 15 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -1167,19 +1167,30 @@ And you'll have to consider the fact that most non-trivial apps share a database
1167
1167
1168
1168
=== 3-state Boolean [[three-state-boolean]]
1169
1169
1170
-
With SQL databases, if a boolean column is not given a default value, it will have three possible values: `true`, `false` and `NULL`.
1170
+
With SQL databases, if a boolean column is nullable, it will have three possible values: `true`, `false` and `NULL`.
1171
1171
Boolean operators https://en.wikipedia.org/wiki/Three-valued_logic[work in unexpected ways] with `NULL`.
1172
1172
1173
1173
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.
1174
1174
1175
-
To avoid such situations, boolean columns should always have a default value and a `NOT NULL` constraint.
1175
+
To avoid such situations, boolean columns should always have a `NOT NULL` constraint.
1176
+
1177
+
Note that when adding a boolean column to an existing table, a default value should be put in place. Otherwise the `NOT NULL` constraint will break for existing rows.
1176
1178
1177
1179
[source,ruby]
1178
1180
----
1179
-
# bad - boolean without a default value
1181
+
# bad - boolean column on a new table without a `NOT NULL` constraint
1182
+
create_table :users do |t|
1183
+
t.boolean :active
1184
+
end
1185
+
1186
+
# bad - adding a boolean without a `NOT NULL` constraint or without a default value
1180
1187
add_column :users, :active, :boolean
1188
+
add_column :users, :active, :boolean, null: false
1181
1189
1182
-
# good - boolean with a default value (`false` or `true`) and with restricted `NULL`
1190
+
# good - boolean with a `NOT NULL` constraint, and a default value (`false` or `true`) for existing tables
0 commit comments