gpt4 book ai didi

ruby-on-rails - Rails 4 : model. where.not 不返回 nil 记录

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:42 24 4
gpt4 key购买 nike

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

我有一个名为 Book 的数据库表,其中包含 category_id(表 Category 的外键)和 author(可变字符 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 的记录。

最佳答案

上次查询的方向正确。

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

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

旁注,在 Rails 5 中,您可以将 ActiveRecord 查询一起使用,因此您可以这样:

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

尽管我认为,在这种情况下,第一个查询更清晰。

关于ruby-on-rails - Rails 4 : model. where.not 不返回 nil 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38441577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com