pluralize without count number in rails 4

15.9k views Asked by At

I am building a blog app. I'd like to be able to pluralize the word "article" if more than one "post" is "published."

Like so: Available Articles or Available Article

This is what I have....

 Available <%=  pluralize @posts.published, "Article" %>:

I've tried

 Available <%=  pluralize @posts.published.count, "Article" %>:

and that works...but I don't want the number. It shouldn't read Available 5 Articles....it should have no number.

6

There are 6 answers

2
jessewmc On BEST ANSWER

I have been looking for the answer to this myself and wasn't satisfied with any of the existing ones. Here's the tidiest solution I found:

 Available <%=  "Article".pluralize(@posts.published.count) %>:

Documentation is here. Relevant bits:

Returns the plural form of the word in the string.

If the optional parameter count is specified,
the singular form will be returned if count == 1.
For any other value of count the plural will be returned.

  'post'.pluralize             # => "posts"
  'apple'.pluralize(1)         # => "apple"
  'apple'.pluralize(2)         # => "apples"
7
jljohnstone On

You can use <%= @posts.published.count > 0 ? "Available Article".pluralize(@posts.published.count) : nil %>:

3
Hetal Khunti On

How about this simple logic? I guess you want to display the number of Article as well if not then simply remove <%= @posts.published.count %>

Available <%= @posts.published.count %> 
    <% if @posts.published.count > 1 %>
        Articles
    <% else %>
        Article
    <% end %>

OR

you can use ternary operator,

Available <%= @posts.published.count %> <%= if (@posts.published.count > 1) ? "Articles" : "Article" %>

Output:

=> Available 1 Article   # if there is only one article 
=> Available 2 Articles   # if there is more then 1 articles 
6
Jakob W On

You could use Rails Internationalization (I18n) to accomplish this. In your config/data/en.yml your translations would be something like this:

en:
  available_articles:
    zero: Available Article
    one: Available Article
    other: Available Articles

And in your view you should be able to get the translation like this:

<%= t(:available_articles, count: @posts.published.count) %> 
0
rld On

Yes, I did that way I liked so much:

- if @post.comments.persisted.any?
    h4
      = t(:available_comments, count: @post.comments.count)
    = render @post.comments.persisted
  - else
    p
      | There are no comments for this post.
en:
  available_comments:
    one: "%{count} Comment"
    other: "%{count} Comments"

Thank's @Jakob W!

1
mangxier On

I found this pluralize has one bug

"user".pluralize(1) => "user"
"user".pluralize(2) => "users"

but

"user".pluralize(0) => "users"