Mit dynamischen Findern angeben NOT NULL
-
01-10-2019 - |
Frage
Ich mag sehr oft dynamischen Finders verwende NOT NULL angeben. So ...
das funktioniert:
Widget.find_all_by_color('blue')
das funktioniert:
Widget.find_all_by_color(nil)
Aber wie kann ich tun
SELECT * FROM `widgets` WHERE `color` IS NOT NULL;
Lösung
Versuchen Sie diese:
Widget.all(:conditions => "color IS NOT NULL")
Andere Tipps
Zwei Möglichkeiten, je nachdem, wie bestimmte Sie sein möchten:
# 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
Ich hoffe, es hilft.
Prost
Widget.find(:all, :conditions => "color IS NOT NULL")
Nicht ganz so elegant, aber dies sollte funktionieren:
Widget.find(:all, :conditions => "'color' IS NOT NULL")
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow