50

我正在构建一个博客应用程序。如果“已发布”不止一个“帖子”,我希望能够将“文章”一词复数。

像这样:可用文章或可用文章

这就是我所拥有的......

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

我试过了

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

这有效......但我不想要这个数字。它不应该阅读可用的 5 篇文章......它应该没有数字。

4

5 回答 5

86

我自己一直在寻找这个问题的答案,对现有的任何一个都不满意。这是我找到的最整洁的解决方案:

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

文档在这里。相关位:

返回字符串中单词的复数形式。

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"
于 2015-02-19T22:36:45.447 回答
12

您可以使用Rails 国际化 (I18n)来完成此操作。在您config/data/en.yml的翻译中将是这样的:

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

在你看来,你应该能够得到这样的翻译:

<%= t(:available_articles, count: @posts.published.count) %> 
于 2014-12-02T14:33:14.043 回答
1

是的,我这样做是我非常喜欢的:

- 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"

谢谢@Jakob W!

于 2018-02-20T17:39:33.497 回答
0

您可以使用<%= @posts.published.count > 0 ? "Available Article".pluralize(@posts.published.count) : nil %>:

于 2014-12-02T05:45:50.447 回答
-1

这个简单的逻辑怎么样?我想你也想显示文章的数量,如果不是那么简单地删除<%= @posts.published.count %>

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

或者

您可以使用 三元运算符

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

输出:

=> Available 1 Article   # if there is only one article 
=> Available 2 Articles   # if there is more then 1 articles 
于 2014-12-02T06:27:48.097 回答