Ruby on Rails ActiveRecord,其中属性不为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11599587/
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
Ruby on Rails ActiveRecord where property is not blank
提问by Jason Yost
I am trying to find records where a specified property is not empty or blank. Since it is a string it is not nil in the database.
我正在尝试查找指定属性不为空或空白的记录。由于它是一个字符串,它在数据库中不是 nil。
Post.where(:sourceurl != '')
The above seems like it should work but I still get records returned where the source_url property is empty. What is the proper way to do this?
以上似乎应该可以工作,但我仍然在 source_url 属性为空的情况下返回记录。这样做的正确方法是什么?
回答by kindofgreat
ActiveRecord (in Rails 3 and 4, i think) allows for checking multiple conditions by passing an Array as an argument. So if you wanted to check for both niland '', you can use:
ActiveRecord(我认为在 Rails 3 和 4 中)允许通过将 Array 作为参数传递来检查多个条件。因此,如果您想同时检查nil和'',您可以使用:
where(sourceurl: [nil, ''])
This will generate an SQL conditional like:
这将生成一个 SQL 条件,如:
(sourceurl IS NULL OR sourceurl = '')
In Rails 4, you can check for the negative condition with .not, so for the original question, you could do:
在 Rails 4 中,您可以使用 .not 检查否定条件,因此对于原始问题,您可以执行以下操作:
Post.where.not(sourceurl: [nil, ''])
.not has a bit of magic that makes it advantageous to a pure SQL query because it works across databases, does NOT NULL queries automatically, and a few more things as explained here: where.not explained
.not 有一点魔法,使它有利于纯 SQL 查询,因为它可以跨数据库工作,不会自动执行 NOT NULL 查询,还有一些解释如下:where.not 解释
回答by abhas
try this
尝试这个
Post.where("sourceurl <> ''")
回答by Abs
Rails 4
导轨 4
Active Record condition:
活动记录条件:
where.not(value: '')
Scope:
范围:
scope :myscope, -> { where.not(value: '') }
回答by Bodhi
The reason your code doesn't work is that your parameter to #whereis
您的代码不起作用的原因是您的参数#where是
:sourceurl != ''
which evaluates to true, as :sourceurl(the symbol) is not equal to ''(an empty string). Thus your code is the same as
其计算结果为true,因为:sourceurl(符号)不等于''(空字符串)。因此您的代码与
Post.where(true)
To elaborate on abhas's answer, both MySQL and PostgreSQL will accept !=and <>as equivalent.
为了详细说明 abhas 的答案,MySQL 和 PostgreSQL 都将接受!=并<>视为等效。
回答by ignar
If that field is NULL by default in your database, I think the better way to resolve it to use plain SQL:
如果该字段在您的数据库中默认为 NULL,我认为解决它的更好方法是使用普通 SQL:
Post.where("sourceurl is not null")
回答by Peter Kordel
In postgresql to catch both empty string and nil you can do:
在 postgresql 中同时捕获空字符串和 nil,您可以执行以下操作:
where("coalesce(sourceurl, '') != ''")

