使用rails(I18n)Api翻译错误消息

问题描述 投票:0回答:1

我正在使用rails internationalization api进行activerecord翻译。我在翻译错误消息时遇到问题。如何从我的项目中的不同文件中翻译多个错误消息?我的application_draft.rb,team.rb,user.rb,todo.rb文件夹中有名为models的文件。我想在其中翻译错误消息,这是我的en.yml文件:

errors:
        models:
         -team:
         -application_draft:
         -conference:
         -todo:
         -user:
            attributes:
              roles:
                too_many_reviewers: too many reviewers
                multiple_sel_error: must not be selected twice
                must_accepted: must have been accepted
                one_app_allowed: Only one application may be lodged
                confirmed_email_address: Please make sure every student confirmed the email address.
                wrong_date_sel: must be a later date than start date
                no_more_than_two: "there cannot be more than 2 students on a team."
                cannot_changed: can't be changed

我已经实现了这个代码并抛出错误(意味着它不起作用)。这是我的application_draft.rbtodo.rb错误代码片段之一:

application.rb:

def different_projects_required
  if project1 && project1 == project2
    errors.add(:projects, :multiple_sel_error)
  end
end

todo.rb

def validate_number_of_reviewers
  errors.add(:user, :too_many_reviewers) if application.todos.count > 3
end

如何翻译这些都避免重复错误?

ruby-on-rails ruby ruby-on-rails-3 activerecord rails-i18n
1个回答
0
投票

从activerecord继承它:

en:
  activerecord:
    errors:
      models:
       -team:
       -application_draft:
       -conference:
       -todo:
       -user:
          attributes:
            roles:
              too_many_reviewers: too many reviewers
              multiple_sel_error: must not be selected twice
              must_accepted: must have been accepted
              one_app_allowed: Only one application may be lodged
              confirmed_email_address: Please make sure every student confirmed the email address.
              wrong_date_sel: must be a later date than start date
              no_more_than_two: "there cannot be more than 2 students on a team."
              cannot_changed: can't be changed

如果它不起作用。我有另一种方式。尝试在方法本身中输入翻译,如下所示

    application.rb:

    def different_projects_required
      if project1 && project1 == project2
        errors.add(:projects, I18n.t('activerecord.errors.models.user.attributes.roles.multiple_sel_error'))
      end
    end

    todo.rb

    def validate_number_of_reviewers
      errors.add(:user, I18n.t('activerecord.errors.models.todo.attributes.roles.too_many_reviewers')) if application.todos.count > 3
    end
© www.soinside.com 2019 - 2024. All rights reserved.