【问题标题】:Customizing rails error messages自定义 Rails 错误消息
【发布时间】:2013-10-24 06:56:58
【问题描述】:

我对 rails4 中验证器的自定义消息有疑问。我有带有设计注册系统的应用程序。我的模型中有一些验证器:

 validates :name, length: {maximum: 45}, presence: true
 validates :surname, length: {maximum: 45}, presence: true
 validates :phone, :phony_plausible => true, presence: true
 validates :company_name, length: {maximum: 100}, presence: true
 validates :address, length: {maximum: 50}, presence: true
 validates :city, length: {maximum: 70}, presence: true
 validates :zip_code, presence: true, length: {is: 6}
 validates :nip, nip: true

当用户留下空白输入名称时,会出现一条消息:

Name can't be blank

当我向验证器添加消息选项时:

  validates :name, length: {maximum: 45}, presence: {message: "Imię nie może być puste"}

我有以下信息:命名 Imię nie może być puste。 我不想在我的消息中包含此名称字词。如何做到这一点?

【问题讨论】:

  • 您使用的是Form_forSimple_form 的哪种rails 形式?
  • 我使用默认的form_for

标签: ruby-on-rails ruby-on-rails-3 devise ruby-on-rails-4


【解决方案1】:

在您的 config/locales/en.yml 中

en: activerecord: attributes: [model_name_goes_here]: [attribute_name_goes here]: "" errors: models: [model_name_goes_here]: attributes: [attribute_name_goes_here]: blank: "Email can't be blank"

例子:

en: activerecord: attributes: user: email: "" errors: models: veteran: attributes: email: blank: "Email can't be blank"

例如,不是显示“电子邮件不能为空白”,而是显示 “不能为空”。本质上,您将“名称:”替换为等于空字符串的别名。您可以将“name:”设置为 name:“Your name”

en: activerecord: attributes: user: name: "Your name"

它会显示“你的名字不能为空”

【讨论】:

  • 添加一些解释,说明此答案如何帮助 OP 解决当前问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2015-09-21
  • 2011-04-27
相关资源
最近更新 更多