簡體   English   中英

如何翻譯活動記錄模型驗證

[英]How to translate active record model validations

當我提交一個包含錯誤的表單時,它會返回一條錯誤消息。 如何使用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

我想翻譯標題和錯誤。

標題的翻譯將是:

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國際化(I18n)API指南中有記錄 ,可能會為您提供更多見解。

只需使用您可以在此處找到的荷蘭語翻譯文件。 它包含大多數(如果不是全部)ActiveRecord驗證消息的翻譯。

將文件復制到項目中的config/locales/

替代方法

如果您想從更新的翻譯中受益,請將以下內容添加到您的Gemfile而不是手動復制翻譯文件:

gem 'rails-i18n'

導軌I18n指南很好地涵蓋了這一點。

您可以在config/locales/nl.yml添加以下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}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM