Rails检查has_many是否存在

时间:2011-04-15 16:27:45

标签: ruby-on-rails has-many

在rails中是否有办法检查查询中的父集合是否为零?我希望得到所有没有孩子的父母。例如:

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

3 个答案:

答案 0 :(得分:5)

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

我更喜欢使用此Railscasts episode中显示的计数器缓存列,并在@PeterWong编写的父模型上获取:children_count

答案 1 :(得分:0)

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

期待看到更好的解决方案。 (我记得有一种方法可以返回一些特定的列而不是Child的完整表。但我不记得方法......)

IMO,因为父母没有孩子意味着父母的id不存在于孩子的parent_id中,所以必须在孩子的parent_id中获取所有ID。

顺便说一下,你可以考虑在父表中添加一个缓存计数器children_count,这样创建或销毁一个孩子就会更新它的父计数器。

在这种情况下,您可以这样做:Parent.where(:children_count => 0)

但是,您必须确保缓存计数器正确且一致,否则结果将不正确。

答案 2 :(得分:0)

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

或类似的东西。