Jas*_*ost 18 activerecord ruby-on-rails ruby-on-rails-3
我试图找到指定属性不为空或空白的记录.由于它是一个字符串,因此在数据库中不是nil.
Post.where(:sourceurl != '')
Run Code Online (Sandbox Code Playgroud)
上面看起来应该可以工作,但我仍然得到返回source_url属性为空的记录.这样做的正确方法是什么?
kin*_*eat 31
我认为ActiveRecord(在Rails 3和4中)允许通过传递Array作为参数来检查多个条件.所以,如果你想同时检查nil和'',你可以使用:
where(sourceurl: [nil, ''])
Run Code Online (Sandbox Code Playgroud)
这将生成一个SQL条件,如:
(sourceurl IS NULL OR sourceurl = '')
Run Code Online (Sandbox Code Playgroud)
在Rails 4中,您可以使用.not检查否定条件,因此对于原始问题,您可以执行以下操作:
Post.where.not(sourceurl: [nil, ''])
Run Code Online (Sandbox Code Playgroud)
.not有一点神奇之处在于它对纯SQL查询有利,因为它可以跨数据库工作,自动执行NOT NULL查询,还有一些其他内容如下所示:where.not explain
Abs*_*Abs 13
Rails 4
活动记录条件:
where.not(value: '')
Run Code Online (Sandbox Code Playgroud)
范围:
scope :myscope, -> { where.not(value: '') }
Run Code Online (Sandbox Code Playgroud)