基于嵌入属性验证Mongoid中的嵌入文档 [英] Validating embedded document in Mongoid based on embedded attribute

查看:60
本文介绍了基于嵌入属性验证Mongoid中的嵌入文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有embeds_many订阅的类订阅者.订阅具有属性状态.我想添加一个状态验证,以便每个订阅者只能有一个订阅具有活动"状态.订阅者可以具有状态为已购买"或已过期"的多个订阅.

I've a class Subscriber which has embeds_many Subscriptions. Subscription has an attribute status. I want to add a validation on status such that only one Subscription can have status 'active' per subscriber. The subscriber can have multiple subscription with status 'purchased' or 'expired' .

推荐答案

这应该做到:

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

但是请确保您始终在订阅者上调用save,否则验证将不会在订阅者上触发,并且您将进入不一致状态.在不一致的状态下,您稍后可能会看到验证失败

But make sure that you always call save on subscriber, otherwise the validations will not fire on subscriber and you will land in an inconsistent state. In an inconsistent state you might see failing validations later

s = Subscriber.create
s.subscriptions.create(status: 'active') # fires validations on subscription only
s.subscriptions.build(status: 'active').save # fires validations on subscription only

如果您还需要验证订阅,则在保存订阅者时,可以级联回调:

If you need to also validate subscription, when saving subscriber, you cascade callbacks:

embeds_many :subscriptions, cascade_callbacks: true

这篇关于基于嵌入属性验证Mongoid中的嵌入文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆