在ActiveRecord查询中测试空字符串

时间:2011-11-13 00:47:34

标签: ruby-on-rails activerecord

在Rails应用程序中,使用ActiveRecord where方法检查属性是零还是空的最简洁方法是什么?

这很有效,但似乎应该有更好的内置方式来实现它:

@items = Item.where :context => nil || ''

当您的搜索包含“where。”等字词时,Google-fu很难做很多事情。

3 个答案:

答案 0 :(得分:16)

你所拥有的东西不会起作用。

@items = Item.where context: nil || ''

确实评估为:

@items = Item.where context: ''

因此,您无法使用此方法找到context设置为nil的项目。

旁注

以这种方式使用thing || other永远不会有效。您无法撰写if item == 'test' || 'something'并希望它可以在item'something'的情况下使用。它仅适用于item'test'的情况。要使这样的事情发挥作用,您需要编写if item == 'test' || item == 'something'。这不是人类说话的方式,而是计算机阅读的方式。

返回主赛事

编写可行的查询的一种方法是:

Item.where("context = ? or context = ?", nil, '')

其内容如下:查找contextnilcontext''的所有项目。

虽然这有效,但并不特别考虑" Rails-y"。更好的方法是:

Item.where(context: [nil, ''])

其内容如下:查找context所在的所有项目。{/ 1}}。

Related question

答案 1 :(得分:1)

您可以使用以下语法:

Item.where(context: [nil, ''])

答案 2 :(得分:0)

我希望通过为这些列设置默认值来避免此问题。

如果那不是您的选择,那么您将需要使用SQL子句。

@items = Item.where "`items`.`context`='' OR `items`.`context` IS NULL"

我使用Squeel gem(http://erniemiller.org/projects/squeel/),这使得OR运算符变得简单易用。我建议检查一下。 Squeel的一个例子是:

@items = Item.where{context.eq('') | context.eq(nil)}