开发者

Using dynamic finders to specify NOT NULL

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 * FR开发者_如何学PythonOM `widgets` WHERE `color` IS NOT NULL;

?


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


Try this:

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


Not quite as elegant, but this should work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜