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?
Rails has a built-in helper for this called
pluralize: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.countvs.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.)