2

我正在使用 Ruby on Rails 3.2.2 和 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_size,即使I18n.locale:it. 我做了一些研究(例如,12),但我仍然无法弄清楚如何正确翻译模型文件中与 Paperclip gem 相关的错误消息(参见上面的代码)。这似乎是 Parperclip gem 的一个错误(也因为这似乎不是唯一一个遇到这个问题的人)......

我该如何解决这个问题?


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

4

2 回答 2

3

Instead of using a lambda in the message parameter can't you simply use the appropriate key in the YAML file? Specifically, wouldn't something like:

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

with an entry in the Italian locale YAML file that looks like

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

with a similar entry in the English local YAML file

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

Assuming your locale is getting set correctly, and that other ActiveRecord localized messages are getting displayed correctly, then I'd expect this to work as Paperclip's validators use the underlying ActiveRecord message bundles via the I18n.t method.

于 2012-08-15T04:46:57.687 回答
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
于 2012-08-15T02:42:31.457 回答