I have a table called scheduled_sessions and a Boolean column called instructor_performed to check if the instructor did teach the class or not.
So I need to find all the records where the instructor didn’t teach the class. But I can’t do this: ScheduledSession.where(:instructor_performed => false) because if the cell is blank, it won’t return that record. I just need all records that are NOT true.
It sounds like your
instructor_performedcolumn can be true, false, or NULL, so you need to query for false or NULL, like this:You could avoid this complexity if you’d set up your database table to disallow null values in that column. You can specify this constraint when you create the table in a migration:
or
Or you can change the constraint for an existing column:
In all of the above, we’re setting the column to allow only true or false values, and we’re telling it to use a default value of false. (Without setting the default, you can’t add a no-nulls constraint because your existing data violates it.)
I almost always disallow nulls when I’m setting up boolean columns (unless I truly want tri-state attributes), because it lets me do this to find everything that’s not true:
Note that other answers (now deleted) that encouraged use of an SQL fragment like
"instructor_performed != true"won’t work because SQL won’t let you use=or!=to match a NULL value. Kind of weird, but them’s the rules. Instead SQL makes you do this:which the above Rails
wherequery hides from you somewhat, as long as you’re still aware that you’re searching for two values.