带轨道的奇怪的I18n日期输出

我的Ruby On Rails 3应用程序中的日期翻译有一个奇怪的问题,我真的不明白为什么……

这是我的en.ymlfr.yml

 fr: date: formats: default: "%d/%m/%Y" short: "%e %b" long: "%e %B %Y" time: formats: default: "%d %B %Y %H:%M:%S" short: "%d %b %H:%M" long: "%A %d %B %Y %H:%M" am: 'am' pm: 'pm' en: date: formats: default: "%Y-%m-%d" long: "%B %d, %Y" short: "%b %d" time: am: am formats: default: ! '%a, %d %b %Y %H:%M:%S %z' long: ! '%B %d, %Y %H:%M' short: ! '%d %b %H:%M' pm: pm 

这不是特定的视图,而是例如我的观点之一:

  :default %> 

我得到那些奇怪的输出:

 With locale = :en => t, 30 o 2012 18:09:33 +0000 With locale = :fr => 30 o 2012 18:09:33 

这些错误的“格式”来自哪里?

我正在使用Rails 3.2.8(使用Postgresql / gem pg), 除了日期之外,与I18n相关的所有内容都能正常工作

谢谢你的帮助 !

我想我终于搞清楚了,抱歉这么久。

Rails l helper只调用I18n.localize 。 如果你追踪I18n.localize代码,你最终会在这里 :

 format = format.to_s.gsub(/%[aAbBp]/) do |match| case match when '%a' then I18n.t(:"date.abbr_day_names", :locale => locale, :format => format)[object.wday] when '%A' then I18n.t(:"date.day_names", :locale => locale, :format => format)[object.wday] when '%b' then I18n.t(:"date.abbr_month_names", :locale => locale, :format => format)[object.mon] when '%B' then I18n.t(:"date.month_names", :locale => locale, :format => format)[object.mon] when '%p' then I18n.t(:"time.#{object.hour < 12 ? :am : :pm}", :locale => locale, :format => format) if object.respond_to? :hour end end 

因此localize helper不会对日期/时间的“stringy”部分使用strftime ,它会尝试自己完成。 如上所述,为月份和日期名称添加翻译(作为YAML中的数组),您的本地化日期和时间应该开始工作。

如果你的YAML中没有那些翻译数组,那么I18n.t(:"date.abbr_month_names")会给你这样的字符串:

 "translation missing: en.date.abbr_month_names" 

然后I18n.localize将最终做这样的愚蠢的事情:

 "translation missing: en.date.abbr_month_names"[10] 

这将使用String#[]而不是预期的Array#[]并且您最终会看到随机查找单个字符的月份和日期名称。

这些错误的“格式”来自哪里?

因为created_at是DateTime,rails使用time格式(不是date )。

https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml#L195

 time: am: am formats: default: ! '%a, %d %b %Y %H:%M:%S %z' 
Interesting Posts