【问题标题】:Rails where not is not finding nil valuesRails 没有找到 nil 值
【发布时间】:2014-12-21 23:34:23
【问题描述】:

我正在尝试搜索帖子值是 false 还是 nil。

Post.where.not(:top_card => true)

这只会返回错误值。我已经确认,如果我执行以下任一操作,它会返回正确的值

Post.where(:top_card => false)

Post.where(:top_card => nil)

知道如何获取 nil 和 false 值的帖子吗?

我是否使用了错误的搜索方法?

【问题讨论】:

  • 试试Post.where(top_card: [false, nil]
  • @Vucko 效果很好,[] 是如何工作的?它是否将它视为一个数组,它只是迭代查找所有值?另外,如果您将其作为答案提交,我将使其正确

标签: ruby-on-rails ruby where


【解决方案1】:

Post.where(top_card: [false, nil]一样使用。

这将产生SELECT * FROM posts WHERE (posts.top_card IN (false, nil))

Rails guides - Subset Conditions 上查看更多信息。

【讨论】:

  • 我认为以下方法也应该有效:Post.where("top_card != ?", true)
  • 我很想知道为什么问题中的代码Post.where.not(:top_card => true) 不起作用?
  • 它应该可以工作。创建一个新问题并发布您的代码。
  • @Humza 不起作用。接受的答案适用于可能性很小的布尔值,但对字符串字段没有帮助,例如User.where.not(status: "active") 不会返回状态为 nil 的用户
【解决方案2】:

Post.where("top_card != ? OR top_card IS NULL")

请注意,这将适用于字符串字段,而@Vucko 接受的答案则不会。即,如果您无法在查询中列出所有选项的详尽列表。

例如这会工作

User.where.not("status != ? OR status IS NULL", "active")

感谢this forum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2020-08-03
    • 2020-05-18
    • 2019-05-03
    相关资源
    最近更新 更多