在Rails 4中使用覆盖错误消息中的值作为自定义validation器

我在Rails 4.2上我编写了一个自定义Validator,它将检查输入的值是否存在于另一个表中。 我一直在审查其他一些post,似乎有一个特定于上下文或rails版本的首选方法来重用被validation的value 。 在rails文档中,我看到例如:

 validates :subdomain, exclusion: { in: %w(www us ca jp), message: "%{value} is reserved." } 

但是,如果我尝试在我的自定义消息覆盖中使用%{value} ,则它不会进行插值,而只是打印“%{value}”。 我见过各种称之为“价值”的方法。 我也无法让%{value} to work in my Validator definition, but could get #{value} to work (New to ruby, if #{value}从validate_each获取它?)。

我一直在努力处理各种格式的validation语句并输入自定义消息。 从文档看起来可重复的一些东西不是。 如果我声明自定义消息的方式导致错误,请告诉我如何更正?

 class ExistingGroupValidator  value).any? record.errors[attribute] << (options[:message] || "#{value} is not a valid group code") end end end class Example  {:message => "The code you have enterd ( **what goes here?** ) is not a valid code, please check with your teacher or group leader for the correct code." } end 

Rails使用国际化样式字符串插值来为消息添加值。 您可以使用I18n.interpolate方法来完成此任务。 像这样的东西应该做的伎俩:

 class ExistingGroupValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless Group.where(:code => value).any? record.errors[attribute] << (I18n.interpolate(options[:message], {value: value}) || "is not a valid group code") end end end class Example < ActiveRecord::Base validates :group_code, presence: true validates :group_code, :existing_group => {:message => "The code you have entered, "%{value}", is not a valid code, please check with your teacher or group leader for the correct code." } end 

Rails会自动将值放在短语的开头,因此您可以这样做:

 class ExistingGroupValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless Group.where(code: value).any? record.errors[attribute] << (options[:message] || 'is not a valid group code') end end end class Example < ActiveRecord::Base validates :group_code, presence: true validates :group_code, existing_group: {message: 'is not a valid code, please check with your teacher or group leader for the correct code.' } end 

另外,请注意,插值不是%总是"#{1+1}"