3

我有一个有 embeds_many 订阅的类订阅者。订阅具有属性状态。我想添加对状态的验证,以便每个订阅者只有一个订阅可以具有“活动”状态。订阅者可以拥有多个状态为 'purchased' 或 'expired' 的订阅。

4

1 回答 1

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
于 2012-10-20T22:24:12.240 回答