我正在尝试检索一些记录,但当我的其中一个参数为空数组时出现问题。我明白为什么查询没有返回任何结果,但我不知道在 Rails 中处理它的最佳方式。在我的代码中,我正在调用
@user.trustees.where(["trustees.default = true AND trustees.id NOT IN (?)", trustees.map{ |t| t.id }])
当 trustees 数组实际包含对象时,这会按预期工作,但是当它不包含对象时,查询将不返回任何内容,因为 SQL 生成的结果为
SELECT `users`.*
FROM `users`
INNER JOIN `trustees` ON `users`.`id` = `trustees`.`trustee_id`
WHERE `trustees`.`truster_id` = 1
AND (trustees.default = true
AND trustees.id NOT IN (NULL))
避免我遇到的 NOT IN (NULL)
问题的最简单方法是什么?
最佳答案
你可以这样做:
@user.trustees.where(default: true).where.not(id: trustees.map{ |t| t.id })
关于activerecord - Rails `NOT IN (null)` 不返回任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176888/