Sql 使用动态查找器指定NOTNULL
我经常想使用动态查找器来指定NOTNULL。所以 这项工作:Sql 使用动态查找器指定NOTNULL,sql,ruby-on-rails,activerecord,dynamic-finders,Sql,Ruby On Rails,Activerecord,Dynamic Finders,我经常想使用动态查找器来指定NOTNULL。所以 这项工作: Widget.find_all_by_color('blue') Widget.find_all_by_color(nil) 这项工作: Widget.find_all_by_color('blue') Widget.find_all_by_color(nil) 但我该怎么办呢 SELECT * FROM `widgets` WHERE `color` IS NOT NULL; ?没有那么优雅,但这应该可以: Widget.
Widget.find_all_by_color('blue')
Widget.find_all_by_color(nil)
这项工作:
Widget.find_all_by_color('blue')
Widget.find_all_by_color(nil)
但我该怎么办呢
SELECT * FROM `widgets` WHERE `color` IS NOT NULL;
?没有那么优雅,但这应该可以:
Widget.find(:all, :conditions => "'color' IS NOT NULL")
试试这个:
Widget.all(:conditions => "color IS NOT NULL")
两种方式取决于您想要的具体程度:
# 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干杯是的,我知道所有这些,谢谢各位。我想用动态查找器是没有办法的。Kandaboggu得到了答案,因为他的答案缩短了5个字符:-D