tbs
tbs

Reputation: 125

Rails check if has_many exist

Is there a way in rails to check to see if a parents collection is nil in the query? I want to get all the parents that don't have any children. Example:

parent_with_no_child = Parent.find(:all, :include => :childs, :conditions => {:childs => :childs.exist?})

Upvotes: 4

Views: 2596

Answers (3)

edthix
edthix

Reputation: 1752

Parent.all( :include => :children, :conditions => "children.parent_id IS NULL")

I prefer to use counter cache column as shown in this Railscasts episode and get the :children_count on Parent model as written by @PeterWong

Upvotes: 5

dogenpunk
dogenpunk

Reputation: 4382

parent_with_no_child = Parent.find(:all,
  :joins => :childs, 
  :group => 'childs.parent_id HAVING COUNT(child.parent_id) = 0')

Or something like that.

Upvotes: 0

PeterWong
PeterWong

Reputation: 16011

Parent.find(Child.all.collect(&:user_id))

Looking forward to seeing better solution. (I remember there is a way to just return some specific columns instead of the full table from Child. But I do not remember the method......)

IMO since parent hasn't child means the parent's id do not exist in child's parent_id, a way to get all ids in child's parent_id would be a must.

BTW, you may consider adding a cache counter children_count to parents table, so creating or destroying a child would update it's parent's counter.

In this case, you may just do this: Parent.where(:children_count => 0)

However, you will have to make sure the cache counter is correct and consistent, or else the result would not be correct.

Upvotes: 0

Related Questions