如何正确翻译Paperclip错误信息?

时间:2012-08-15 01:53:30

标签: ruby-on-rails ruby ruby-on-rails-3 internationalization paperclip

我正在使用Ruby on Rails 3.2.2和Paperclip插件。由于我想翻译Paperclip错误消息,我使用以下代码:

class Article < ActiveRecord::Base
  validates_attachment_size :picture,
    :less_than => 4.megabytes,
    :message   => I18n.t('trl_too_big_file_size', :scope => 'activerecord.errors.messages')
end

我的.yml个文件是:

# <APP_PATH>/config/locales/en.yml (english language)
activerecord:
  errors:
    messages:
      trl_too_big_file_size: is too big

# <APP_PATH>/config/locales/it.yml (italian language)
activerecord:
  errors:
    messages:
      trl_too_big_file_size: è troppo grande

我的ApplicationController是:

class ApplicationController < ActionController::Base
  before_filter :set_locale

  def set_locale
    # I am using code from http://guides.rubyonrails.org/i18n.html#setting-and-passing-the-locale.
    I18n.locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
  end
  # BTW: My `I18n.default_locale` is `:en` (english).
end

然而,当我提交与Paperclip附件相关的表单时,我的应用程序会生成翻译文本 - 也就是说,它会生成(并输出)正确翻译的字符串,因为即使en.activerecord.errors.messages.trl_too_big_file_sizeI18n.locale,它也始终引用默认的语言环境语言错误字符串:it。我做了一些研究(例如,12),但我仍然无法弄清楚如何正确翻译模型文件中与Paperclip gem相关的错误消息(参见上面的代码)。这似乎是Parperclip宝石的一个错误(也因为看起来我不是唯一一个得到这个问题的人)......

我该如何解决这个问题?


P.S。:我认为这个问题与ApplicationController-Paperclip gem的一些“文件加载顺序进程”有关...但我不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:3)

不是在message参数中使用lambda而不是简单地使用YAML文件中的相应键吗?具体来说,不会像:

class Article < ActiveRecord::Base
  validates_attachment_size :picture,
    :less_than => 4.megabytes
end

在意大利语语言环境YAML文件中有一个类似于

的条目
it:
  activerecord:
    errors:
      models:
        article:
          attributes:
            picture:
              less_than: è troppo grande

在英文本地YAML文件中有类似的条目

en:
  activerecord:
    errors:
      models:
        article:
          attributes:
            picture:
              less_than: is too big

假设您的语言环境设置正确,并且其他ActiveRecord本地化消息正确显示,那么我希望这可以正常工作,因为Paperclip的验证器通过I18n.t方法使用基础ActiveRecord消息包。

答案 1 :(得分:0)

您可能需要使用lambda作为消息吗?

请参阅https://github.com/thoughtbot/paperclip/pull/411

class Article < ActiveRecord::Base
  validates_attachment_size :picture,
    :less_than => 4.megabytes,
    :message => lambda { 
      I18n.t('trl_too_big_file_size', :scope => 'activerecord.errors.messages') 
    }
end
相关问题