Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-5622

#reload after mutating embeds_many field does not reset internal state

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Critical - P2 Critical - P2
    • 9.0.0, 8.0.5, 8.1.1
    • Affects Version/s: None
    • Component/s: Persistence
    • Labels:
      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}"
      

            Assignee:
            jamis.buck@mongodb.com Jamis Buck
            Reporter:
            jason.penny@braze.com Jason Penny
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: