Rails ActiveRecord查找属性不是给定值的子节点
鉴于Parent
有很多具有status_id
属性的Child
,我想找到所有没有status_id:1
。 换句话说, status_id
可以是nil
或不同的值。 但我看到一些有趣的行为:
Parent.find(1).childs.where(status_id:nil) => #<ActiveRecord::AssociationRelation [#] Parent.find(1).childs.where.not(status_id:1) => #
这篇文章建议SQL将NULL,缺少某些东西视为不能等于存在的东西。
MySQL中10个不能按预期工作的东西有一个例子,需要使用“IS”进行空检查,如下所示。
Parent.find(1).childs.where("status_id != ? or status_id is null", 1)
这工作:
Parent.find(1).childs.where("status_id IS NOT 1")
尽管如此,仍然会喜欢解释原因
如果行不存在,将通过exception查找
parent = Parent.where(id: 1).includes(:childs).first parent.childs.where("status_id IS NOT 1") if parent.present?