在Rails应用程序中,使用ActiveRecord where
方法检查属性是否为空或空的最清洁方法是什么?测试ActiveRecord查询中的空字符串
这工作,但似乎应该有一个更好的,内置的方式做到这一点:
@items = Item.where :context => nil || ''
很难做与谷歌福,当你搜索包括像“,其中条款。 “
在Rails应用程序中,使用ActiveRecord where
方法检查属性是否为空或空的最清洁方法是什么?测试ActiveRecord查询中的空字符串
这工作,但似乎应该有一个更好的,内置的方式做到这一点:
@items = Item.where :context => nil || ''
很难做与谷歌福,当你搜索包括像“,其中条款。 “
你可以使用这个语法:
Item.where(context: [nil, ''])
我喜欢设置这样的列的默认值来避免这个问题。
如果这不是您的选择,那么您将需要使用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)}
你有什么行不通。
@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, '')
这读作:找到的所有项目,其中context
是nil
或context
是''
。
虽然这个工作,它并不特别被认为是“Rails-y”。更好的办法是:
Item.where(context: [nil, ''])
这为读取:找到的所有项目,其中context
是[nil, '']
。
你'where'确实有点复杂的事情,但确实['.blank?()'](http://api.rubyonrails.org/classes/Object.html#method-i-空白-3F)帮助你呢? – sarnold
上面的代码在哪里? 'Item.where:context.blank?()'返回一个未过滤的列表,并且'Item.where:context => .blank?()'抛出一个语法错误。 –
'@items = Item.where:context => nil || '''不会检查空值,因为'nil || '''计算结果只是'',所以得到的查询将只是'SELECT * FROM items WHERE context =''' – stereoscott