Rails的distance_of_time_in_words方法返回"en, about_x_hours"。

7

我遇到了一个奇怪的问题,希望有人知道是什么原因...

使用distance_of_time_in_words(以及time_ago_in_words)没有返回实际的时间距离。相反,它返回类似于“en,about_x_hours”或“en,x_minutes”的内容。

模式是正确的,例如:

time_ago_in_words(50.minutes.ago) => "en, about_x_hours"
time_ago_in_words(3.minutes.ago) => "en, x_minutes"

但是为什么它显示的是“x”而不是实际数字,“_”代替空格,并且在所有这些内容的开头都有“en,”?!


奇怪...我在Rails 3.0.1和2.2.2上都尝试过,它们都显示“大约1小时”。 - nonopolarity
绝对奇怪...顺便说一下,我正在运行2.3.8...如果有区别的话。我的无知猜测是它与国际化有关?我猜“en”表示应该是英语?不知道...瞎猜的。 - Steven Ou
3个回答

10

这将通过I18n gem返回一个要翻译的字符串.... 请尝试以下操作:

# I18n.localize(string)
I18n.l time_ago_in_words(3.minutes.ago)

如果不存在,添加以下内容到

# config/locales/en.yml
en:
  datetime:
    distance_in_words:
      ...
      less_than_x_minutes:
        one: "less than a minute"
        other: "less than %{count} minutes"
      x_minutes:
        one: "1 minute"
        other: "%{count} minutes"
      about_x_hours:
        one: "about 1 hour"
        other: "about %{count} hours"
      ....

请确保在您的en.yml文件中包含以下(可能是自定义的)数据:

http://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml

请告诉我它是否有效。


1
以上代码给出了以下错误:对象必须是日期、日期时间或时间对象。给定的是“大约x分钟”。 - Steven Ou
我尝试了更新的代码,但仍然出现错误:对象必须是日期、日期时间或时间对象。给定的是"<span class="translation_missing">en, x_minutes</span>"。:( - Steven Ou
所以我终于弄明白了。谢谢你的帮助!没有你我就做不到!虽然我仍然困惑为什么它没有正常工作...似乎其他人都没有问题... - Steven Ou

4

我终于让它工作了!希望这能帮助任何遇到相同问题的人...

基本上,Lichtamberg所说的一半是正确的。en.yml必须如下所示:

en:
  x_minutes:
    one:   "1 minute"
    other: "%{count} minutes"

请注意,x_minutes不属于datetime,它有oneother。此外,在distance_of_time_in_words方法中已经实现了I18n,因此不需要使用I18n.l。因此,只需使用上述内容(以及Lichtamberg包含的所有其他关于_x_hours、x_days等模式),即可执行以下操作:
time_ago_in_words(3.minutes.ago)

好了...就这样!


1
从Rails控制台中,使用helper.time_ago_in_words(3.minutes.ago) - Magne

0

无耻地抄袭 time_ago_in_words => "在{{count天内。"?}}

Rails在助手中使用了一些已弃用的语法,这些语法在最新的Ruby版本中被删除。如果您正在使用像Heroku这样的东西,请尝试告诉您的生产实例使用Rails 2.3.9。否则,您也可以尝试降级Ruby。

请参阅更改日志:http://weblog.rubyonrails.org/2010/9/4/ruby-on-rails-2-3-9-released

Changes i18n named-interpolation syntax from the deprecated Hello {{name}} to the 1.9-native Hello %{name}.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接