自定义验证的本地化

Localization of custom validations

我正在开展一个项目,我想将应用中使用的所有字符串移动到一个文件中,以便可以轻松更改和更新它们。但是我在自定义验证方面遇到了麻烦。我在我的应用程序中进行了如下验证:

validate :thing_is_correct

def thing_is_correct
  unless thing.is_correct
    errors[:base] << "Thing must be correct"
  end
end

我不确定如何将 "Thing must be correct" 移入我的 en.yml 文件并移出模型。任何帮助将不胜感激。

您可以访问模型内​​部的 I18n。

validate :thing_is_correct

def thing_is_correct
  unless thing.is_correct
    errors[:base] << I18n.t('mymodel.mymessage')
  end
end

里面config/locales/en.yml

en:
  mymodel:
    mymessage: "Thing must be correct"

在另一个语言环境中:(config/locales/es.yml)

es:
  mymodel:
    mymessage: "Esto debe ser correcto"

如果设置I18n.locale = :en,则显示en.yml内的信息。如果你设置为:eses.yml里面的那个将被使用。

Rails 方法是使用 the mechanism described in the Guides

errorsActiveModel::Errors 的实例。可以通过调用 ActiveModel::Errors#add 添加新消息。正如您在文档中看到的那样,您不仅可以传递消息,还可以传递表示错误的符号:

def thing_is_correct
  unless thing.is_correct?
    errors.add(:thing, :thing_incorrect)
  end
end

Active Model 将自动尝试从指南中描述的名称空间中获取消息(请参阅上面的 link)。实际消息是使用 ActiveModel::Errors#generate_message.

生成的

总结一下:

  1. 使用errors.add(:think, :thing_incorrect)
  2. the YAML keys listed in the Guides 之一下添加 thing_incorrect