-1

I would like to add this functionality to my rails app. This is the schema. I do not know how to write this code.

if
<%= @post.comments.count == 1 %>
puts 'Comment'

else
puts 'Comments'

For example:

1 Comment

5 Comments

Please help.

1
  • 1
    try using pluralize method "Comment".pluralize(@post.comments) or in your way you can try @post.comments.count == 1 ? "Comment" : "Comment".pluralize Apr 9, 2015 at 12:26

4 Answers 4

3

Rails has a built in helper which handles inflection (guessing how to pluralize english words).

pluralize(@post.comments.count, 'Comment')

http://apidock.com/rails/ActionView/Helpers/TextHelper/pluralize

1

You can do it like so:

 <% if @post.comments.count == 1 %>
     <%= Comment %>

 <% else %>
     <%= Comments %>
 <% end %>

Though you would be better off using the 'pluralize' method if this is indeed your use case.

 <%= pluralize(@post.comments.count, 'Comment') %>
0

Better solution can be using pluralize method:

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

In your way, ternary operator looks more suitable in your case.

<%= @post.comments.count == 1 ? 'Comment' : 'Comments' %>
0

Use the String method pluralize "Comment".pluralize(@post.comments.count)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.