我有一个包含embeds_many订阅的类订阅者。订阅具有属性状态。我想在状态上添加一个验证,以便每个订阅者只有一个订阅可以具有“活动”状态。订户可以具有多个订阅,其状态为“已购买”或“已过期”。
答案 0 :(得分:2)
这应该这样做:
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