如何在Rails 3.1中国际化(I18n)失败验证时的通用错误消息



我希望能够提供国际化的,有用的错误消息。

我有一个通用的错误消息,部分视图呈现嵌套表单提交

    # _error_messages.html.erb - Fragment
    ...
    <strong><%= t('errors.template.body') %> </strong>       
    <ul>
      <% object.errors.full_messages.each do |msg| %>
        <li><%= msg %> </li>
      <% end %>
    </ul>
    ...

我得到了国际化的正文消息,但是,我不知道如何替换属性,或者更具体地说,不知道如何替换模型字段(即validates_presence_of:name)验证的":blank"错误,尽管进行了多次yaml迭代。

这是我的yaml的一个片段

en:
  errors: &errors
    format: ! '%{attribute} -- %{message}'
      messages:
        accepted: must be accepted
        blank: must not be blank
        body: ! 'There were problems with the following fields:'

    activemodel:
        attributes:
          family_wizard: 
            children: kids

我这样写yaml是因为当我检查传递给partial的错误对象时当我将子元素的名称字段留空时(:validates_presence_of:name)看起来像这样:

#<ActiveModel::Errors:0x007111111C111111 @base=#<FamilyWizard id: nil, ...>, 
    @messages {:children=>["must not be blank"]}>

但是我能得到的唯一错误信息是:

以下字段有问题:

  • Children——不能为空

理想的解决方案错误消息应该是这样的:

以下字段有问题:

  • Kids名称不能为空

这个Stack Overflow问题(如何在Rails 3.2.3中本地化通用错误消息部分?)是在正确的轨道上,但它缺少我想要的activemodel/activerecord验证部分。

这个问题的答案是我有错误的作用域,因为我的yaml文件有两个问题。错误的间距和错误的标签。它应该是activerecord而不是activmodel,并且activerecord的作用域应该与树中的错误作用域处于同一级别。

要翻译模型的属性(即,Children To Kids), yaml看起来像这样:

en:
  errors: &errors
    format: ! '%{attribute} -- %{message}'
      messages:
        accepted: must be accepted
        blank: must not be blank
        body: ! 'There were problems with the following fields:'

  activerecord:
    attributes:
      family_wizard: 
        children: kids

帮助我得到答案的两个资源是:

  • 我如何在错误消息中翻译表单字段名称?

最新更新