-
Type: Bug
-
Resolution: Fixed
-
Priority: Critical - P2
-
Affects Version/s: None
-
Component/s: Persistence
-
None
-
Fully Compatible
Loading a parent model and mutating an embeds_many field with assign_attributes, then calling reload on the parent is not resetting internal state (delayed_atomic_sets I think) such that a save after the reload will save the earlier mutation
For example:
# frozen_string_literal: true require "mongoid" class Child include Mongoid::Document end class Parent include Mongoid::Document embeds_many :children validate :custom_validation def custom_validation self.validates_length_of(:children, maximum: 2) end end Mongoid.connect_to("mongoid_test") Mongoid.purge! p = Parent.create!(children: [Child.new, Child.new]) puts "Created parent with 2 children" puts "p.valid? #{p.valid?}" puts puts "Adding another child" p.assign_attributes(children: p.children + [Child.new]) puts "now p.valid? #{p.valid?}" puts puts "Reloading parent" p.reload puts "reload did reset the embeds_many 'current' value: p.valid? #{p.valid?}" puts puts "There should be no updates since we just reloaded but atomic_updates is not empty:" puts " atomic_updates:", p.atomic_updates puts puts "Calling p.save" p.save puts puts "the parent was saved in an invalid state" p2 = Parent.first puts "Parent.first.valid? #{p2.valid?}" puts "Parent.first.children.length #{p2.children.length}"