问题
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