When you’re using a boolean in Rails with Active Record, and you ask (say) visible?, it checks the column for whether it is true or not. If it is false or nil, visible? will return false.
How do you scope a boolean to ask if the ? method would return false? I have this:
scope :visible, where(hide: [nil, false])
but am wondering if there is a cleaner way. Is there a way to write this scope without explicitly saying both nil and false? If we were after the opposite, we could just write
scope :invisible, where(hide: true)
which seems cleaner. What’s the best code for the visible scope?
Use a default value on the column. This is good for two reasons: you have only two possible values in your DB, making your code easier. And booleans are either true or false, not nil, not maybe, not foobar. True and false. “I’d rather avoid having to get the DB strictly false/true though” is a moot argument for a boolean column.
If you need more than 2 states, use a state machine or something similar – then its not a boolean column/state anymore.