Rails ActiveRecord find children where attribute is NOT a given value

回眸只為那壹抹淺笑 提交于 2020-01-06 05:09:05

问题


Given that a Parent has many Childs 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 []>

回答1:


This post suggests that SQL treats NULL, the absence of something, as something that can't be equal to something that exists.

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 != ? or status_id is null", 1)




回答2:


This worked:

Parent.find(1).childs.where("status_id IS NOT 1")

Would still love an explanation as to why though




回答3:


find will through an exception if row is not present

parent = Parent.where(id: 1).includes(:childs).first
parent.childs.where("status_id IS NOT 1") if parent.present?


来源:https://stackoverflow.com/questions/38258316/rails-activerecord-find-children-where-attribute-is-not-a-given-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!