使用动态查找器指定 NOT NULL

发布于 2024-09-07 17:32:05 字数 279 浏览 7 评论 0原文

我经常想使用动态查找器来指定 NOT NULL。所以...

这有效:

Widget.find_all_by_color('blue')

这有效:

Widget.find_all_by_color(nil)

但我该怎么办

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

I very often want to use dynamic finders to specify NOT NULL. So…

this works:

Widget.find_all_by_color('blue')

this works:

Widget.find_all_by_color(nil)

But how can I do

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

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你的背包 2024-09-14 17:32:06

两种方法取决于您想要的具体程度:

# 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

我希望它有所帮助。

干杯

Two ways depending on how specific you want to be:

# 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

I hope it helps.

Cheers

恏ㄋ傷疤忘ㄋ疼 2024-09-14 17:32:06
Widget.find(:all, :conditions => "color IS NOT NULL")
Widget.find(:all, :conditions => "color IS NOT NULL")
萤火眠眠 2024-09-14 17:32:06

试试这个:

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

Try this:

Widget.all(:conditions => "color IS NOT NULL")
挽清梦 2024-09-14 17:32:06

不太优雅,但这应该有效:

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

Not quite as elegant, but this should work:

Widget.find(:all, :conditions => "'color' IS NOT NULL")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文