james james - 25 days ago 6
Ruby Question

Count all child objects across class

If a model

Parent
has two child models:
AChild
and
BChild
such that:

@parent.a_childs.count = 1
@parent.b_childs.count = 2


Is there an existing method such that:

@parent.count_all_children = 3

Answer

Assuming that the Parent model has_many associates AChild and BChild, this is a solution for any number of child models. Drop the following method into the Parent model file:

def count_all_children
  counts = []
  Parent.reflect_on_all_associations(:has_many).each do |assoc|
    counts << self.public_send(assoc.name).count
  end
  counts.sum
end

That uses reflection and may be relatively slow. If you only have those two child models and don't intend to add (m)any more, then just sum the two:

def count_all_children
  self.a_childs.count + self.b_childs.count
end
Comments