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

どの程度具体的にしたいかによって、次の 2 つの方法があります。

# 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.all(:conditions => "color IS NOT NULL")
于 2010-06-30T20:52:50.350 に答える
1

それほどエレガントではありませんが、これはうまくいくはずです:

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