icon 《基础 Ruby on Rails》的示例程序asagao与Rails2.2相适应

错误信息的国际化(4)

继续上一章的错误信息的国际化这一主题。

这一章,针对用英语和日语表示像“存在1个输入错误”这样的,嵌入数字型的错误信息的方法进行说明。


asagao 应用程序的 app/views/accounts/_errors.rhtml 中有如下叙述(第五行)。

<div id="errorExplanationHeader"><%= member.errors.length %>个错误信息存在。</div>

将之做如下修改。

<div id="errorExplanationHeader"><%= t('activerecord.errors.template.header',
  :count => member.errors.length) %></div>

接下来,将config/locale/activerecord_ja.yml 做如下修改。

ja:
  activerecord:
    (省略)
    errors:
      (省略)
      models:
        member:
          taken: 与其它重复。
          attributes:
            password:
              confirmation: 密码错误。
            uploaded_image:
              too_large: "尺寸过大(最大64KB)。"
      template:
        header: "{{count}}个输入错误存在。"

而且,将config/locale/activerecord_en.yml 做如下修改。

en:
  activerecord:
    (省略)
    errors:
      (省略)
      models:
        member:
          attributes:
            uploaded_image:
              too_large: "is too large (maximum is 64KB)"
      template:
        header:
          one:    "There is an error"
          other:  "There are {{count}} errors"

_errors.rhtml 中赋予 t 方法的 :count 选项的值,嵌入信息中{{count}} 的部分。

虽然在 《基础 Ruby on Rails》 没有利用,但是在最早的 Rails 中是有叫做 error_messages_for 的辅助方法的。

Rails 2.2 中,这一方法也被国际化了。

事实上,翻译文件的关键字 activerecord.errors.template.header 是与这个error_messages_for 中使用的错误信息相对应的。

然而,英语的情况下,因为根据错误的个数是一个还是两个以上形式会改变,header 下,设置oneother 两个子关键字的时候,有必要具备两个信息。

根据count 的个数需要改变信息时,你可以指定以下子关键字。

  • zero
  • one (单数)
  • two (双数)
  • few (Paucal)
  • many
  • other

详细内容请参照 unicode.org 的 Language Plural Rules


尽管和这次的主题无关,我也想顺便说一下,我发现要表示帐户的编辑表单的话,密码栏会通过浏览器auto-complete(自动完成)。

总之,登录时,如果记住密码的话,编辑表单的密码栏也会自动获得值。

这个情况不太好。

app/views/accounts/edit.rhtml 的65 行变成如下。

      <div><%= form.password_field :password, :size => 30 %></div>

把这个进行如下修改的话,自动完成变成 off 。

      <div><%= form.password_field :password, :size => 30, :autocomplete => 'off' %></div>

(2009/01/24)