新手问题 请教如何对验证的错误提示信息,进行本地化

huopo125 · March 29, 2014 · Last by huopo125 replied at March 29, 2014 · 3031 hits

在看敏捷开发过程中,想将 rails 应用汉化,在对 errors 信息显示上遇到错误信息: translation data {:address=>"住址", :name=>"姓名", :email=>"邮箱", :pay_type=>"支付方式"} can not be used with :count => 1 1.zh-CN.yml

zh-CN:
  errors:
    template:
      body: "错误信息如下:"
      header:
        one: "%{model}有1个错误!"
        other: "%{model}有%{count}个错误!"
  activerecord:
    models:
      order: "订单"
      attributes:
      order:
        address: "住址"
        name: "姓名"
        email: "邮箱" 
        pay_type: "支付方式"

2.view <h2><%= raw t('errors.template.header', count: @order.errors.count, model: t('activerecord.models.order')) %>.</h2>

非常感谢朋友们的帮助,希望我这个新手早日成为一名高手,哈哈。 此问题已经解决,通过各位的指点,发现问题是出在我没有注意书中对 attributes 的缩进上,有点惭愧。 正确的格式是:

activerecord:
  models:
    order: "订单"
  attributes:
    order:
      address: "住址"
      name: "姓名"
      email: "邮箱" 
      pay_type: "支付方式"

'errors.template.header' 这个词条没出现在你贴的 yml 文件里啊。

#1 楼 @Rei 因为这一条没有出错,所以没有贴上来;当我将 activerecord.models.order 删除以后,就可以正常显示,不过是‘Name 请将信息填写完整'形式的,无法对‘Name’进行替换。我自己判断是无法对中文复数化,不知对不?

我觉得你误解了 t 的用法,t 'errors.template.header' 的意思是找到 'errors.template.header' 这个词条,后面的参数是作为变量传到词条字符串里的。在顶楼信息中 'errors.template.header' 并不是一个词条,或者 t 有什么高级用法我不知道。

你如果要输出 model 的校验信息,应该用 model.errors.full_messages 来取得,里面已经指定了对应词条和属性名字。

http://guides.rubyonrails.org/i18n.html#active-model-methods

ActiveModel::Errors#full_messages prepends the attribute name to the error message using a separator that will be looked up from errors.format (and which defaults to "%{attribute} %{message}").

#5 楼 @Rei 谢谢指点,,我对 t 的用法不熟悉,只是看着《web 敏捷开发之道》做的,只是将其西班牙语本地化变为中文本地化。我再学习学习。

t('errors.template.header')的结果是

{
  :one => "%{model}有1个错误!",
  :other => "%{model}有%{count}个错误!"
}

t 出来的不是字符串,所以后面传的 count 和 model 参数都废了,如果想传参只能分开写 t('errors.template.header.other', count: @order.errors.count)

#7 楼 @dddd1919 谢谢了,学习了

You need to Sign in before reply, if you don't have an account, please Sign up first.