En utilisant trouveurs dynamiques pour spécifier NOT NULL
-
01-10-2019 - |
Question
Je veux bien souvent utiliser trouveurs dynamiques pour spécifier NOT NULL. Alors ...
travaux:
Widget.find_all_by_color('blue')
travaux:
Widget.find_all_by_color(nil)
Mais comment puis-je faire
SELECT * FROM `widgets` WHERE `color` IS NOT NULL;
La solution
Essayez ceci:
Widget.all(:conditions => "color IS NOT NULL")
Autres conseils
Deux façons selon la façon spécifique que vous voulez être:
# 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
J'espère que ça aide.
Vive
Widget.find(:all, :conditions => "color IS NOT NULL")
Pas tout à fait aussi élégant, mais cela devrait fonctionner:
Widget.find(:all, :conditions => "'color' IS NOT NULL")
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow