使用rails(I18n)Api翻译错误消息
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用rails(I18n)Api翻译错误消息相关的知识,希望对你有一定的参考价值。
我正在使用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.rb
和todo.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
如何翻译这些都避免重复错误?
答案
从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
以上是关于使用rails(I18n)Api翻译错误消息的主要内容,如果未能解决你的问题,请参考以下文章