Rails 4:从自定义验证器的错误消息中删除属性名称

Rails 4: remove attribute name from error message in custom validator

在我的 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.

如何从上面的消息中删除单词 "copy"?

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

有什么想法吗?

不幸的是,目前 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}"

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