Rails ActiveRecord查找属性不是给定值的子级 [英] Rails ActiveRecord find children where attribute is NOT a given value
问题描述
考虑到父母
有许多 Child
s并带有 status_id
属性,我想查找所有没有 status_id:1
的孩子。换句话说, status_id
可以为 nil
或其他值。但我看到了一些有趣的行为:
Given that a Parent
has many Child
s with status_id
attribute, I want to find all the children that do NOT have a status_id:1
. In other words, the status_id
could be nil
or a different value. But I'm seeing some interesting behavior:
Parent.find(1).childs.where(status_id:nil)
=> #<ActiveRecord::AssociationRelation [#<Child id: 1, status_id: nil ...>]
Parent.find(1).childs.where.not(status_id:1)
=> #<ActiveRecord::AssociationRelation []>
推荐答案
这篇文章表示SQL处理NULL,缺少某些内容,因为它不能等于存在的事物。
This post suggests that SQL treats NULL, the absence of something, as something that can't be equal to something that exists.
在MySQL中有10项无法正常工作的示例要求使用 IS进行空检查,如下所示。
10 things in MySQL that won’t work as expected has an example which requires using "IS" for null check, something like below.
Parent.find(1).childs.where( status_id!=?或status_id为null,1)
这篇关于Rails ActiveRecord查找属性不是给定值的子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!