Rails check if has_many exist
Is there a way in rails to check to se开发者_开发知识库e 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?})
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
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.
parent_with_no_child = Parent.find(:all,
:joins => :childs,
:group => 'childs.parent_id HAVING COUNT(child.parent_id) = 0')
Or something like that.
精彩评论