6

我知道你可以使用复数功能在 Rails 中复数一个单词。

pluralize (3, 'cat')
=> 3 cats

但我想做的是复数一个需要复数多个单词的句子。

There are <%= Cat.count %> cats

问题在于,如果只有 1 只猫。它会回来

There are 1 cats

这在语法上没有意义。

应该说

There are x cats (if x is not 1)

There is 1 cat (if there is only 1)

问题是,我不知道如何复数,因为这里有两个参数(is 和 cat)。

任何帮助将不胜感激。

也许是这样的?

if Cat.count == 1
  puts "There is 1 cat"
else
  puts "There are #{Cat.count} cats"
end
4

1 回答 1

15

您可以通过将计数值定义为翻译键(即 )来利用库的复数功能I18nconfig/locales/en.yml

en:
  cats:
    one: 'There is one cat.'
    other: 'There are %{count} cats.'

然后,在您的代码中(或视图,或其他任何地方,因为I18n是全球可用的)

3.times{|i|
  puts I18n.t('cats', count: i)
}

将输出

There are 0 cats.
There is one cat.
There are 2 cats.
于 2014-07-31T17:39:23.617 回答