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

时间:2015-12-18 01:20:22

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

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

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.

如何删除单词&#34; copy&#34;从上面的消息?

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

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

不幸的是,目前错误的full_messages格式是由一个I18n密钥errors.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}"

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