繁体   English   中英

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.

如何从上述消息中删除“复制”一词?

我在验证器中尝试了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}"

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM