ActiveRecord:如何将属性值插值到自定义验证错误消息? [英] ActiveRecord: How to interpolate attribute value to a custom validation errror message?
问题描述
我有一个 validates_presence_of:price
验证,它返回一个书籍版本价格不能为空
验证失败时出现错误。
I have a validates_presence_of :price
validation, which returns a "Book version price can't be blank"
error when the validation fails.
class BookVersion < ActiveRecord::Base
attr_accessible :name, :book_id, :instock, :isbn, :price, :famis_price, :famis_number, :weight_in_pounds,
:width, :height, :thickness
validates_presence_of :price, message: "can't be blank"
不过,我想将BookVersion的 name
值添加到验证消息中,如下所示:
However, I want to add the name
value of the BookVersion to the validation message like so:
如果 book_version .name
返回 LB:
图书版本LB价格不能为空
所以我想做类似的事情:
So I want to do something like:
validates_presence_of :price, message: "#{self.name} can't be blank"
但这正在返回图书版本价格BookVersion不能为空
,这不是我想要的
but that is returning Book version price BookVersion can't be blank
, which isn't what I want
推荐答案
您返回BookVersion的原因是因为在这一点上,验证的范围仅限于Class而不是您要验证的对象。这就是在ActiveModel验证中设置消息的方式。如果您确实希望验证执行您想要的操作,则可以编写以下内容:
The reason you are getting back BookVersion is because at this point, the validation is scoped to the Class and not the object you are validating. This is just how setting a message in ActiveModel validations works. If you really want the validation to do what you want you could write something like:
validate :presence_of_price
private
def presence_of_price
errors.add(:price, "for #{self.name} can't be blank") if price.blank?
end
这篇关于ActiveRecord:如何将属性值插值到自定义验证错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!