【问题标题】:Rails 4: model.where.not does not return nil recordsRails 4:model.where.not 不返回 nil 记录
【发布时间】:2016-07-18 16:17:54
【问题描述】:

我进行了谷歌搜索,发现与我的问题here 类似的问题,但是,我仍然不知道应该是什么解决方案。我的情况如下:

我有一个名为Book 的数据库表,其中有category_id(表Category 的外键)和author(varchar 255)。我需要通过category_id 查询此表,但不包括某些作者的姓名。示例:获取 category_id = 10 的所有书籍,但不包括作者 John Doe 的书籍:

books = Book.where(category_id: 10).where.not(author: 'John Doe')

或

books = Book.where(category_id: 10).where("author != ?", "John Doe")

这两个查询对我有用,除了作者为nil 的那些记录。我还需要让这些查询返回具有nil 作者的记录。

【问题讨论】:

  • 你试过了吗? books = Book.where(category_id: 10).where("author ? OR author = ?", "John Doe", nil)
  • NULL 未知,因此您需要根据@chrismanderson 的回答具体说明。

标签: ruby-on-rails ruby postgresql


【解决方案1】:

您在最后一个查询中走在了正确的轨道上。

Book.where(category_id: 10).where("author != ? OR author IS NULL", "John Doe")

这应该可以满足您的要求。

旁注,在 Rails 5 中,您可以使用 or 和 ActiveRecord 查询,所以您可以这样:

Book.where(category_id: 10).where.not(author: 'John Doe').or(where(author: nil))

虽然我认为,在这种情况下,第一个查询更清楚。

【讨论】:

  • 对于 Rails 4 中更面向对象的方法,您还可以使用 this gem。请参阅this example 获取灵感。
  • 这里的原因是'x'=NULL 是假的,但'x'!=NULL 也是假的。基本上NULL不等于也不等于包括它自己在内的其他值,所以IS NULL是必需的。
猜你喜欢
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-22
  • 2014-03-24
  • 1970-01-01
  • 2018-02-27
相关资源
最近更新 更多