2016-07-08 52 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?