【发布时间】:2016-06-23 08:36:59
【问题描述】:
我有一个模特StudentProductRelationship。我正在添加一个自定义验证器
validate :validate_primary_product , :if => "!primary_product"
方法是
def validate_primary_tag
unless StudentProductRelationship.exists?(:primary_product => true, :student_id => student_id)
errors.add(:base,"There is no primary product associated to product")
else
end
end
primary_product 是一个布尔字段。我想为student_id 验证至少存在一个真实的primary_product。问题是如果我有一个StudentProductRelationship 对象说spr 和primary_product = true。如果我这样做spr.update_attributes(primary_product: false)。验证不会引发错误,因为StudentProductRelationship.exists?(:primary_product => true, :student_id => student_id) 存在,因为spr 仍然存在于带有primary_product = true 的数据库中。如何超越?
【问题讨论】: