【问题标题】:How to translate active record model validations如何翻译活动记录模型验证
【发布时间】:2023-03-22 08:38:01
【问题描述】:

当我提交包含错误的表单时,它会返回错误消息。如何使用 i18n 翻译这些错误消息?在我看来,我已经翻译了所有其他文本,所以我知道 l18n 在 Rails 中是如何工作的。我现在明白了:

2 errors prohibited this user from being saved:

Email translation missing: nl.activerecord.errors.models.user.attributes.email.blank
Email translation missing: nl.activerecord.errors.models.user.attributes.email.blank

我想同时翻译标题和错误。

【问题讨论】:

    标签: ruby-on-rails activerecord internationalization


    【解决方案1】:

    只需使用荷兰语翻译文件即可find here。它包含大多数(如果不是全部)ActiveRecord 验证消息的翻译。

    将文件复制到项目中的config/locales/

    替代方法

    如果您想从更新的翻译中受益,请将以下内容添加到您的Gemfile,而不是手动复制翻译文件:

    gem 'rails-i18n'
    

    【讨论】:

    • 这通常是我在创建新的 rails 应用程序时要做的第一件事,你知道是否有办法自动完成吗?
    • 不知道,真的!为它开始一个新问题;)
    • 这个插件看起来不错:github.com/zargony/rails-i18n-updater,不过我没有测试过。
    • @Benoit,只需将 rails-i18n gem 添加到您的 Gemfile。
    • 另外,还有一个类似的 gem,叫做 devise-i18n,所有的翻译都用于设计。
    【解决方案2】:

    标题的翻译是:

    nl:
      activerecord:
        errors:
          template:
            header:
              one:   "1 error prohibited this %{model} from being saved"
              other: "%{count} errors prohibited this %{model} from being saved"
            body:    "There were problems with the following fields:"
    

    为了翻译错误信息,Rails 将使用以下翻译顺序:

    activerecord.errors.models.user.attributes.name.blank
    activerecord.errors.models.user.blank
    activerecord.errors.messages.blank
    errors.attributes.name.blank
    errors.messages.blank
    

    所以你可以添加:

    nl:
      activerecord:
        errors:
          models:
            user:
              attributes:
                email:
                  blank: "foo blank in nl bar baz"
    

    它记录在Rails Internationalization (I18n) API Guide 中,这可能会给您更多的见解。

    【讨论】:

    • 正确,我没有真正注意到。我将删除管理部分以澄清。谢谢!
    【解决方案3】:

    rails I18n guide 很好地涵盖了这一点。

    您可以在config/locales/nl.yml 中输入以下内容来翻译属性:

    nl:
      activerecord:
        models:
          user: "User"
        attributes:
          email: "Email"
    

    对于错误消息,ActiveRecord 将在以下命名空间中查找它们:

    activerecord.errors.models.[model_name].attributes.[attribute_name]
    activerecord.errors.models.[model_name]
    activerecord.errors.messages
    errors.attributes.[attribute_name]
    errors.messages
    

    modelattributevalue 在您的翻译中插入并可用,例如:

    nl:
      errors:
        messages:
          blank: "Please fill the %{model}'s %{attribute}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多