質問

ダイナミックファインダーを使用して、nullではないことを指定したいと思うことがよくあります。それで…

これは機能します:

Widget.find_all_by_color('blue')

これは機能します:

Widget.find_all_by_color(nil)

しかし、どうすればよいですか

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

?

役に立ちましたか?

解決

これを試して:

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

他のヒント

あなたがどれだけ具体的になりたいかに応じて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

私はそれが役立つことを願っています。

乾杯

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

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

Widget.find(:all, :conditions => "'color' IS NOT NULL")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top