Ruby-on-rails activerecord 搜索条件 - 查找 null 或 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1481467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
activerecord search conditions - looking for null or false
提问by Daniel
When doing a search in active record I'm looking for record's that do not have an archived bit set to true.
在活动记录中进行搜索时,我正在寻找未将存档位设置为 true 的记录。
Some of the archived bits are null (which are not archived) others have archived set to false.
一些存档位为空(未存档),其他存档设置为 false。
Obviously,
明显地,
Project.all(:conditions => {:archived => false})
misses the projects with the archived bits with null values. How can all non-archived projects be selected wtih active record?
错过了存档位为空值的项目。如何通过活动记录选择所有未归档的项目?
采纳答案by Ron DeVera
Try this (in Rails 2):
试试这个(在 Rails 2 中):
Project.all(:conditions => ['archived IS NULL OR archived = ?', false])
This is a limitation of older versions of Rails, as explained here: https://rails.lighthouseapp.com/projects/8994/tickets/1181-ar-find-producing-null-when-it-should-be-is-null
这是旧版本 Rails 的限制,如下所述:https: //rails.lighthouseapp.com/projects/8994/tickets/1181-ar-find-production-null-when-it-should-be-is-空值
回答by TJChambers
Rails 4 (possibly earlier) supports:
Rails 4(可能更早)支持:
Project.where(archived: [false, nil])
... which is quite concise.
......这是非常简洁的。
回答by sean_j_roberts
The proper database agnostic way to do this is:
执行此操作的正确数据库不可知方法是:
Project.where("archived IS NULL OR archived = ?", false)
回答by morgoth
@metasoarous
@metasorous
Try:
尝试:
Project.all(:conditions => "archived IS NULL OR archived = 'F'")
回答by Micha?l Witrant
If you want to be database agnostic, you can do this in Rails 3:
如果你想成为数据库不可知论者,你可以在 Rails 3 中做到这一点:
Project.where("archived IS NULL OR archived = #{ActiveRecord::Base.connection.quoted_false}")

