【问题标题】:Rails Error messages with attributes regarding their genders带有关于其性别属性的 Rails 错误消息
【发布时间】:2013-10-22 01:32:36
【问题描述】:

我正在为我的 Rails 应用程序 (pt.yml) 编写翻译,该应用程序用葡萄牙语翻译所有 activerecord 错误消息。

  activerecord:
    models:
      user: Usuário
      feedback: Contato
  attributes:
    user:
      password: "senha"
      phone_number: "celular"
      first_name: "nome"
      last_name: "sobrenome"
      password_confirmation: "Confirmação de senha"
    feedback:
      title: "Título"
      name: "Nome"
      message: "Mensagem"
    report:
      before_photo: "A foto do foco"
  errors:
    template:
      header:
        one: "1 erro impediu que o %{model.model_name.human} fosse salvo"
        other: "%{count} erros impediram que o %{model}  fosse salvo"
    messages:
      blank: "é obrigatório."
      confirmation: "não confere."
      empty: "é obrigatório."
      exclusion: "está reservado."
      invalid: "não é válido."
      taken: "já está em uso."
      too_long: "é muito longo. (mínimo de %{count} caracteres)"
      too_short: "é muito curto. (mínimo de %{count} caracteres)"
      not_a_number: "não é um número."

问题是属性可以是阳性或阴性,错误信息应该取决于他们的性别。例如,“é obrigatório 或 é obrigatória”。当我们产生错误消息时,是否有一个简单的解决方案来处理属性的性别?

【问题讨论】:

  • 我面临同样的问题,我认为没有简单的方法可以做到这一点。您可以运行自己的验证方法,然后根据性别添加错误消息。如果您找到更好的方法,请告诉我:)

标签: ruby-on-rails activerecord internationalization translation


【解决方案1】:

我意识到我可以为每个模型的每个属性使用不同的错误消息。 config/locales/pt.yml 看起来像这样:

pt:
    activerecord:
        models:
            user: Usuário
        attributes:
            password: "Senha"
            first_name: "Nome"
        errors:
            models:
                user:
                    attributes:
                        password:
                            blank: "é obrigatória."
                        first_name:
                            blank: "é obrigatório."

所以 pt -> errors -> models -> #{model_name} -> attributes -> #{attribute_name} 将为每个属性指定这些自定义性别特定错误消息的位置。希望这可以帮助任何人:)

【讨论】:

    【解决方案2】:

    这更像是一种解决方法,而不是问题的适当解决方案,但如果您不太担心,这可能是拉丁衍生语言的一个很好的提示。

    我还努力尝试使形容词与属性的性别匹配(这个问题在英语中不存在),然后我发现我应该始终引用该字段:

    Female attribute -> The field must not be blank
    Male attribute -> The field must be whatever
    

    这样,您将获得DRY更好的方法。

    特别是在葡萄牙语的情况下,我的意思是:

      # ActiveRecord
      errors:
        messages:
          empty: "O campo é obrigatório."
          blank: "é campo obrigatório." # another idea
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多