我在Rails 4.2上我编写了一个自定义Validator,它将检查输入的值是否存在于另一个表中。我一直在审查其他一些帖子,似乎有一个特定于上下文或rails版本的首选方法来重用正在验证的value
。在rails docs我看到例如:
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
获取validate_each
#{value}?)。
我一直在努力使用各种格式的验证语句并输入自定义消息。从文档看起来可重复的一些东西不是。如果我声明自定义消息的方式导致错误,请告诉我如何更正?
class ExistingGroupValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless Group.where(:code => value).any?
record.errors[attribute] << (options[:message] || "#{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 enterd ( **what goes here?** ) is not a valid code, please check with your teacher or group
leader for the correct code." }
end
答案 0 :(得分:-1)
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}"
总是%
,而不是{{1}}。