views:

36

answers:

2

I have a line of code in a basic Rails blog application I did that determines whether the suffix to the number of comments should be "comment" (if 1) or "comments" (0 or 2+)

Currently, it is a line in the view looking like this:

    <%= post.comments.count() %> <%= post.comments.count() == 1 ? "comment" : "comments" -%>

However, since I wrote that I have done some more studying, and realized that this logic shouldn't actually go in the view.

Am I right to assume that the real place for this is in the posts helper?

How can I implement it?

+2  A: 

Rails has a built-in helper for this called pluralize:

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

This will automatically print e.g. "1 comment" or "4 comments."

P.S. In Ruby parentheses around method arguments are usually optional, and when you're not passing any arguments it's conventional to leave off the parentheses, i.e. comments.count vs. comments.count(). (You should, of course, use parentheses when it helps to reduce ambiguity for other people reading your code--but that's almost never necessary when you're not passing any arguments.)

Jordan
Shouldn't `comment` be quoted?
j.
It is now... =P
j.
Well well, look at that. Nice.Thanks for the heads up on parentheses as well.
Sebastian Öhrn
+1  A: 

Jordan's answer is what you'll want to do in this particular case.

To answer your question, this is probably depends on your preference. If the pluralize helper didn't exist and you had to use code like the above, there really isn't an issue with putting it in the view. If you want to display the comment count in multiple places, that would go in a partial. For this specific case, I think putting it in a helper isn't necessary - it's a quick one liner. If it was any bigger or more complicated then you'd put it in a helper.

ryeguy