只有在使用Mongoid嵌入文档时才保留文档?

问题描述:

我有一个2级嵌套窗体(很像this)与以下类。我遇到的问题是,当我没有添加任何时间间隔(最深的嵌入式文档)时,我不希望第二个最深的文档被保存。在所有者中,我添加了一个拒绝语句来检查是否有任何间隔正在传递,这是有效的。只有在使用Mongoid嵌入文档时才保留文档?

但是,当时间表最初有间隔时,但他们在表单中销毁时(通过传递_destroy:true),时间表也需要销毁。什么是最好的方法来做到这一点?我希望避免在文档被保存后破坏文档的时间表上回调。

class Owner 
    include Mongoid::Document 
    embeds_many :schedules 

    attr_accessible :schedules_attributes 

    accepts_nested_attributes_for :schedules, allow_destroy: true, reject_if: :no_intervals? 

    def no_intervals?(attributes) 
    attributes['intervals_attributes'].nil? 
    end  
end 

class Schedule 
    include Mongoid::Document 
    embeds_many :intervals 
    embedded_in :owner 

    attr_accessible :days, :intervals_attributes 

    accepts_nested_attributes_for :intervals, 
           allow_destroy: true, 
           reject_if: :all_blank 
end 

class Interval 
    include Mongoid::Document 
    embedded_in :schedule 
end 

更新:也许这是最好的形式本身?如果所有时间间隔都标记为_destroy:true,则还可以使用_destroy:true标记时间表。但理想的解决方案是客户不可知的。

如何增加这个给船东类:

before_update do 
    schedules.each |schedule| 
    schedule.destroy if schedule.intervals.empty? 
    end 
end 
+0

谢谢!这就是我所要做的,问题在于,所有者类或其嵌入式文档中的变化需要通过系统“涟漪化”(reindexing elasticsearch和其他),因此它很快变得非常昂贵。 – Yeggeps