# Counting blog comments

**URL:** <https://www.ruby-forum.com/t/counting-blog-comments/175711>\
**Category:** Rails\
**Created:** [September 18, 2009, 8:00am UTC](https://www.ruby-forum.com/t/counting-blog-comments/175711 "2009-09-18T08:00:07Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mark](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@mark](https://www.ruby-forum.com/u/mark)\
**Post date:** [September 18, 2009, 8:00am UTC](https://www.ruby-forum.com/t/counting-blog-comments/175711/1 "2009-09-18T08:00:07Z")

</div>

I have “posts” and “comments”, and I’d like to display the number of  
comments each post has (and display 0 if none). In the index Posts  
view, I display a list of posts and their authors using the below  
partial. What I can’t figure out is how to limit the comment count to  
the post listing (my attempts so far show the total number of comments  
in the database). How do I limit the count?

partial:

\<% div\_for post do %\>

## 

**\<%= link\_to\_unless\_current h(post.title), post %\>**

```
<font size="1">created by <%= post.user %> <%= time_ago_in_words

```

(post.created\_at) %\> ago  
  
  
\<%= post.body %\>

  
\<% end %\>

Many thanks!  
Mark

---

<div class="post-metadata">

**Author:** ![mark](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@mark](https://www.ruby-forum.com/u/mark)\
**Post date:** [September 18, 2009, 9:36am UTC](https://www.ruby-forum.com/t/counting-blog-comments/175711/2 "2009-09-18T09:36:08Z")

</div>

I think, you must have Post-'has many"-Comments relationship

So, to find number of comments:  
post.comments.count will give you total number of comments of a post.

-Gourav

---

<div class="post-metadata">

**Author:** ![mark](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@mark](https://www.ruby-forum.com/u/mark)\
**Post date:** [September 18, 2009, 5:07pm UTC](https://www.ruby-forum.com/t/counting-blog-comments/175711/3 "2009-09-18T17:07:31Z")

</div>

That did it. I think I’ve been staring at the monitor too  
long… 🙂

---

<div class="post-metadata">

**Author:** ![mark](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e9c0ed/32.png) [@mark](https://www.ruby-forum.com/u/mark)\
**Post date:** [September 18, 2009, 6:11pm UTC](https://www.ruby-forum.com/t/counting-blog-comments/175711/4 "2009-09-18T18:11:20Z")

</div>

Depending on performance needs, you can also look at the counter\_cache  
option for the ActiveRecord association.

Your current approach has to query the child table to get the count,  
which could be a performance hit on a big site.  
Don’t prematurely optimize though - it’s just good to know about other  
options in case the need arises.
