counting blog comments

1 view
Skip to first unread message

Mark

unread,
Sep 18, 2009, 1:58:31 AM9/18/09
to Ruby on Rails: Talk
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 %>
<p><strong><%= link_to_unless_current h(post.title), post %></strong>
-
<font size="1">created by <%= post.user %> <%= time_ago_in_words
(post.created_at) %> ago
</font><br />
<%= post.body %></p>
<% end %>

Many thanks!
Mark

Gourav

unread,
Sep 18, 2009, 3:34:12 AM9/18/09
to Ruby on Rails: Talk
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

Mark

unread,
Sep 18, 2009, 11:05:11 AM9/18/09
to Ruby on Rails: Talk
That did it. I think I've been staring at the monitor too
long... :-)

E. Litwin

unread,
Sep 18, 2009, 12:09:32 PM9/18/09
to Ruby on Rails: Talk
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.
Reply all
Reply to author
Forward
0 new messages