2

我经常想使用动态查找器来指定 NOT NULL。所以……</p>

这有效:

Widget.find_all_by_color('blue')

这有效:

Widget.find_all_by_color(nil)

但是我该怎么办

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

?

4

4 回答 4

3

两种方法取决于您想要的具体程度:

# 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

我希望它有所帮助。

干杯

于 2010-07-01T10:02:37.980 回答
2
Widget.find(:all, :conditions => "color IS NOT NULL")
于 2010-06-30T20:23:26.280 回答
1

不太优雅,但这应该可以工作:

Widget.find(:all, :conditions => "'color' IS NOT NULL")
于 2010-06-30T20:22:47.423 回答
1

试试这个:

Widget.all(:conditions => "color IS NOT NULL")
于 2010-06-30T20:52:50.350 回答