2016-07-08 4 views
1

Parentにはという属性を持つChildがたくさんあると仮定して、status_id:1を持たないすべての子供を探したいと思います。換言すれば、status_idnilであってもよいし、異なる値であってもよい。しかし、私はいくつかの興味深い行動見ている: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

答えて

1

This postは、SQLは、何かの不在をNULLとして扱うことを示唆しているのに理由を説明するのが大好きです存在するものと同等ではないものとして、

10 things in MySQL that won’t work as expectedには、ヌルチェックに「IS」を使用する必要がある例があります。

Parent.find(1).childs.where("status_id != ? or status_id is null", 1)

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? 
関連する問題