2016-07-08 53 views
1

鉴于Parent有许多Child s和status_id属性,我想查找所有没有status_id:1的孩子。换句话说,status_id可能是nil或不同的值。但我看到了一些有趣的现象:Rails ActiveRecord查找儿童,其中属性不是给定值

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

你可以写为:'Parent.find(1).childs.where( “!STATUS_ID = 1”)'或 'Parent.find(1).childs.where(“status_id!=?”,1)' –

+0

@KhanhPham即不工作....仍然得到'=>#' – james

回答

0

这工作:

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

仍然会爱一个解释,为什么虽然

0

发现将通过行是否不存在异常

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