我有一个embeds_many订阅的类订阅者。订阅具有属性状态。我想添加一个状态验证,以便每个订阅者只有一个订阅可以具有“活动”状态。订阅者可以具有状态为“已购买”或“已过期”的多个订阅。
最佳答案
应该这样做:
class Subscriber
include Mongoid::Document
embeds_many :subscriptions
validate :active_subscriptions
def active_subscriptions
self.errors.add(:base, 'too many active subscriptions') if
subscriptions.where(status: 'active').count > 1
end
end
class Subscription
include Mongoid::Document
embedded_in :subscriber
field :status, class: 'String'
end
s = Subscriber.create
s.subscriptions.build(status: 'active')
s.save # fires validations on subscriber
s.subscriptions.build(status: 'active')
s.save # wouldn't save
但是请确保始终调用“保存在订户上”,否则验证将不会在订户上触发,并且您将进入不一致状态。在不一致状态下,您稍后可能会看到验证失败
s = Subscriber.create
s.subscriptions.create(status: 'active') # fires validations on subscription only
s.subscriptions.build(status: 'active').save # fires validations on subscription only
如果还需要验证订阅,则在保存订阅者时,可以级联回调:
embeds_many :subscriptions, cascade_callbacks: true