【问题标题】:Rails 4: remove attribute name from error message in custom validatorRails 4:从自定义验证器的错误消息中删除属性名称
【发布时间】:2016-03-24 15:52:41
【问题描述】:

在我的 Rails 4 应用程序中,我在 Post 模型上实现了一个名为 LinkValidator 的自定义验证器:

class LinkValidator < ActiveModel::Validator

  def validate(record)
    if record.format == "Link"
      if extract_link(record.copy).blank?
        record.errors[:copy] << 'Please make sure the copy of this post includes a link.'
      end
    end
  end

end

一切正常,除了目前显示的消息是:

1 error prohibited this post from being saved:
Copy Please make sure the copy of this post includes a link.

如何去掉上面留言中的“复制”二字?

我在验证器中尝试了record.errors &lt;&lt; '...' 而不是record.errors[:copy] &lt;&lt; '...',但验证不再有效。

有什么想法吗?

【问题讨论】:

  • 将错误添加到base而不是copy
  • 非常感谢您的评论。不过,我不确定我是否跟随。你的意思是我应该写record.errors[:base]而不是record.errors[:copy]
  • 是的,没错。看guides.rubyonrails.org/…
  • 完美,这确实解决了问题。你想建议这个作为答案吗?我很乐意接受。
  • 没关系。这很可能是重复的,但我似乎找不到重复的问题。

标签: ruby-on-rails validation ruby-on-rails-4 activemodel


【解决方案1】:

不幸的是,目前full_messages 的错误格式由单个I18nerrors.format 控制,因此对其进行任何更改都会产生全球性后果。

常见的选项是将错误附加到基础而不是属性,因为基础错误的完整消息不包括属性人名。我个人不喜欢这个解决方案的原因有很多,主要是如果验证错误是由字段 A 引起的,它应该附加到字段 A。这才有意义。期间。

虽然这个问题没有很好的解决办法。肮脏的解决方案是使用猴子补丁。将此代码放在 config/initializers 文件夹中的新文件中:

module ActiveModel
  class Errors
    def full_message(attribute, message)
      return message if attribute == :base
      attr_name = attribute.to_s.tr('.', '_').humanize
      attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
      klass = @base.class
      I18n.t(:"#{klass.i18n_scope}.error_format.#{klass.model_name.i18n_key}.#{attribute}", {
                                 :default   => [:"errors.format", "%{attribute} %{message}"],
                                 :attribute => attr_name,
                                 :message   => message
                             })
    end
  end
end

这保留了 full_messages 的行为(根据 rails 4.0),但是它允许您覆盖特定模型属性的 full_message 的格式。因此,您可以在翻译中的某处添加这一点:

activerecord:
  error_format:
    post:
      copy: "%{message}"

老实说,我不喜欢没有干净的方法来做到这一点,这可能值得一个新的宝石。

【讨论】:

  • 嗨,我将如何使用它进行存在验证?我让它为 :picture 属性工作,但是当我提交一个空白字段时,我得到了这个 {:picture=&gt;"%{message}"}
猜你喜欢
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
  • 1970-01-01
  • 2011-07-19
相关资源
最近更新 更多