views:

65

answers:

3

Hey everyone,

This is probably pretty basic, but I'm trying to figure out how to show how many comments a post has in rails, on the post index page of my app.

comments belongs_to post, and post has_many comments

Just not sure how to show on the index page, the amount of comments for each post.

Thanks in advance!

Elliot

+4  A: 

Try this.

<%= post.comments.size %>

You might also be interested in the pluralize method.

<%= pluralize(post.comments.size, 'comment') %>

This will output "3 comments" or "1 comment", etc.

ryanb
Thanks a ton! Worked like a charm!
Elliot
post.comments.size will take longer to query than post.comments.count(:all), see below.
klochner
@klochner, it is the same. "count" and "size" will both use a count(*) query for a has_many association.
ryanb
+3  A: 

I may be wrong here, but you should use

<%= post.comments.count %> rather than size.

ActiveRecord knows that 'count' is a special method, and will turn it into a SELECT count(id) from comments where post_id = x (which is what you want).

size however, is not a special method, and ActiveRecord will load all the comments into an array in memory (SELECT * from comments where post_id = x, and then tell you how long this array is, which may be unneccessary - if you're going to loop through the array of comments further down the page, then you may want to use size to load them into memory, because it will need to happen later anyway.

Orion Edwards
size will also use COUNT (at least it did when i just tested it)
tliff
I just tested it and size used select *, while count used select count(*). It may depend on the relation - mine was habtm.
klochner
you may be right, i tested it with a has_many relation
tliff
I prefer to always use "size" on a has_many association. I know back in Rails 2.1 the "count" method would not take advantage of a counter cache if it was present. This may have changed in 2.3.
ryanb
A: 

You should also use some of ActiveRecord's built in functionality here. The counter_cache. Check it out here

railsninja