【问题标题】:Testing for an empty string in an ActiveRecord query在 ActiveRecord 查询中测试空字符串
【发布时间】:2011-11-13 00:47:34
【问题描述】:

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

这行得通,但似乎应该有一种更好的内置方式来做到这一点:

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

当您的搜索包含“哪里”之类的字词时,很难使用 Google-fu 做很多事情。

【问题讨论】:

  • 您的where 确实使事情复杂了一点,但.blank?() 对您有帮助吗?
  • 在上面的代码中会去哪里? Item.where :context.blank?() 返回一个未过滤的列表,Item.where :context => .blank?() 抛出一个语法错误。
  • @items = Item.where :context => nil || '' 不会检查空值,因为 nil || '' 的计算结果仅为 '',因此生成的查询将只是 SELECT * FROM items WHERE context = ''

标签: ruby-on-rails activerecord


【解决方案1】:

你拥有的东西是行不通的。

@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[nil, ''] 中的所有项目。

Related question

【讨论】:

  • 我想同时考虑 ""'' 所以我制作了类似 Item.where("context = ? or context = ? or context = ?", nil, '', "") 的东西。很快发现我不需要 ""'' 因为它们在 Ruby 眼中是平等的。
【解决方案2】:

您可以使用以下语法:

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

【讨论】:

    【解决方案3】:

    我喜欢通过为这些列设置默认值来避免这个问题。

    如果这不适合您,那么您需要使用 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)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      相关资源
      最近更新 更多