8f93a872e399bc1353cc8d4e791d5401

Can ActiveRecord be used to abstract this more nicely across databases?

1
2
3
class MyModel
  named_scope :not_hidden, :conditions => ['hidden IS NULL OR hidden = 0 OR hidden = ?', 'f']
end

Refactorings

No refactoring yet !

8f93a872e399bc1353cc8d4e791d5401

mislav

June 19, 2008, June 19, 2008 19:44, permalink

No rating. Login to rate!

When NULL value is not allowed, this is adequate:

1
2
3
class MyModel
  named_scope :not_hidden, :conditions => { :hidden => false }
end
8f93a872e399bc1353cc8d4e791d5401

mislav

June 19, 2008, June 19, 2008 19:46, permalink

No rating. Login to rate!

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
085541f9546d0505433183b5f95bbf62

Ryan Bates

June 19, 2008, June 19, 2008 23:26, permalink

3 ratings. Login to rate!

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
F288a8afe5302a16a366d5e9d34f2fec

Joe Grossberg

June 29, 2008, June 29, 2008 00:41, permalink

No rating. Login to rate!

Change your model, so that there is no NULL, and that it defaults to 0.

821395fe70906c8290df7f18ac4ac6cf

rick

June 30, 2008, June 30, 2008 08:49, permalink

No rating. Login to rate!

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 :)

E635ccff7389d9070f5e7e9fe8b36beb

rpheath

July 1, 2008, July 01, 2008 00:00, permalink

No rating. Login to rate!

I agree with Ryan B...

Avatar

lel

July 17, 2008, July 17, 2008 22:58, permalink

No rating. Login to rate!

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"

Your refactoring





Format Copy from initial code

or Cancel