1 2 3
class MyModel named_scope :not_hidden, :conditions => ['hidden IS NULL OR hidden = 0 OR hidden = ?', 'f'] end
Refactorings
No refactoring yet !
mislav
June 19, 2008, June 19, 2008 19:44, permalink
When NULL value is not allowed, this is adequate:
1 2 3
class MyModel named_scope :not_hidden, :conditions => { :hidden => false } end
mislav
June 19, 2008, June 19, 2008 19:46, permalink
When you have to support NULL value and treat is as false in this particular case:
1 2 3
class MyModel named_scope :not_hidden, :conditions => ['hidden IS NULL OR hidden = ?', false] end
Ryan Bates
June 19, 2008, June 19, 2008 23:26, permalink
I prefer to add ":null => false" database constraint on all booleans to avoid this problem. It's too easy to miss the null condition and that can lead to some very tricky bugs.
1
change_column :my_models, :hidden, :null => false
Joe Grossberg
June 29, 2008, June 29, 2008 00:41, permalink
Change your model, so that there is no NULL, and that it defaults to 0.
rick
June 30, 2008, June 30, 2008 08:49, permalink
I third the suggestion. "hidden IS NULL or hidden = 0" skips your db indexes. I just did the same thing in a couple of my apps :)
lel
July 17, 2008, July 17, 2008 22:58, permalink
If you use migrations to create the columns in the db, then AR will map the ruby boolean via the adapter to whatever native way the db uses.
i.e. t.boolean :hidden, :default => false
Then {:hidden => false} will always work.
1 2 3 4 5 6 7 8
# OT: the :conditions can handle AND, OR and BETWEEN. # array is OR, comma is AND, range is BETWEEN :conditions => {:hidden => [nil, 0, 'f'], :name => "abc", :age => (18..65) } # which is much better than :conditions => "(hidden IS NULL OR hidden = 0 OR hidden = 'f') AND name = 'abc' AND age >= 18 AND age <= 65"
Can ActiveRecord be used to abstract this more nicely across databases?