Generally, you can use the #count
method on any has_many
association to get the count. For example:
Category.find(1, :include => :discussions).discussions.first.comments.count
Edit:
A "brute force" approach to counting all the comments on a particular Category:
category = Category.find(1, :include => { :discussions => :comments }) # Check that this eager loading doesn't cause unnecessary overhead.
count = 0
category.discussions.map{|d| count += d.comments.count}
Note that this will create N+1 queries and therefore might not be a performant option. An alternative is to set a counter cache column on the Discussion model and then do this instead:
category = Category.find(1, :include => :discussions)
count = 0
category.discussions.map{|d| count += d.comments_count}
Edit (2):
You can further simplify the summation bit by using the Array#inject
method. See example here: How to sum array of numbers in Ruby?