Question

I very often want to use dynamic finders to specify NOT NULL. So…

this works:

Widget.find_all_by_color('blue')

this works:

Widget.find_all_by_color(nil)

But how can I do

SELECT * FROM `widgets` WHERE `color` IS NOT NULL;

?

Was it helpful?

Solution

Try this:

Widget.all(:conditions => "color IS NOT NULL")

OTHER TIPS

Two ways depending on how specific you want to be:

# in your model
class Widget < ActiveRecord::Base
  # first way
  named_scope :coloured, {:conditions => ["color IS NOT NULL"]}
  # second way
  named_scope :not_null, lambda{|*args| (field=args.first ? {:conditions => ["#{field} is not null",field]} : {}) } }
end

# in your controller
@coloured_widgets = Widget.coloured.all           # using first way
@coloured_widgets = Widget.not_null(:colour).all  # using second way

I hope it helps.

Cheers

Widget.find(:all, :conditions => "color IS NOT NULL")

Not quite as elegant, but this should work:

Widget.find(:all, :conditions => "'color' IS NOT NULL")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top