Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby on Rails ActiveRecord,其中属性不为空_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails Ruby on Rails ActiveRecord,其中属性不为空

Ruby on rails Ruby on Rails ActiveRecord,其中属性不为空,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我正在尝试查找指定属性不为空或为空的记录。因为它是一个字符串,所以在数据库中不是nil Post.where(:sourceurl != '') 上面的代码看起来应该可以工作,但是我仍然得到返回的记录,其中source_url属性为空。正确的方法是什么?如果数据库中该字段默认为空,我认为更好的解决方法是使用纯SQL: Post.where("sourceurl is not null") 试试这个 Post.where("sourceurl <> ''") Post.where

我正在尝试查找指定属性不为空或为空的记录。因为它是一个字符串,所以在数据库中不是nil

Post.where(:sourceurl != '')

上面的代码看起来应该可以工作,但是我仍然得到返回的记录,其中source_url属性为空。正确的方法是什么?

如果数据库中该字段默认为空,我认为更好的解决方法是使用纯SQL:

Post.where("sourceurl is not null")
试试这个

Post.where("sourceurl <> ''")
Post.where(“源URL”)

您的代码不起作用的原因是您的参数to
#where
不起作用

:sourceurl != ''
其计算结果为
true
,因为
:sourceurl
(符号)不等于
“”
(空字符串)。因此,您的代码与

Post.where(true)

为了详细说明abhas的答案,MySQL和PostgreSQL都将接受
=
等效。

Rails 4

活动记录条件:

where.not(value: '')
范围:

scope :myscope, -> { where.not(value: '') }

在postgresql中,要捕获空字符串和nil,可以执行以下操作:

where("coalesce(sourceurl, '') != ''")
ActiveRecord(我认为在Rails 3和4中)允许通过将数组作为参数传递来检查多个条件。因此,如果要同时检查
nil
'
,可以使用:

where(sourceurl: [nil, ''])
这将生成SQL条件语句,如:

(sourceurl IS NULL OR sourceurl = '')
在Rails 4中,您可以使用.not检查否定条件,因此对于原始问题,您可以执行以下操作:

Post.where.not(sourceurl: [nil, ''])

.not有一点魔力,使其对纯SQL查询有利,因为它可以跨数据库工作,不会自动为查询设置空值,还有一些事情,如此处所述:

@steel请阅读问题…问题是字符串…整数可以使用
Post.where(“sourceurl不为空”)
似乎不适用于postgres..反正我发布了对我有用的东西!此处详述:第9.13.2节包括空格。您介意解释一下它的作用吗?只是在答案中添加一些代码并没有多大帮助。感谢您修复我的代码格式;我已经有一段时间没有回答问题了。让我编辑一下答案。我已经在Rails工作了10年,而你让我大吃一惊。不知道我怎么还不知道。我总是求助于原始SQL,比如
。其中(“posts.sourceurl为NULL或posts.sourceurl=”)
。谢谢不要使用。在Rails 4中,这将产生
值!=空