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

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

 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. 

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

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

任何的想法?

不幸的是,目前错误的full_messages格式是用一个I18nerrors.format ,因此对它的任何改变都会产生全局性的后果。

常见选项是将错误附加到基础而不是属性,因为基本错误的完整消息不包含属性人名。 我个人不喜欢这个解决方案的原因,主要是如果validation错误是由字段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。