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

Autosave load all relations after_save

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.0.1
    • Affects Version/s: None
    • Component/s: None
    • None

      Using autosave: true on a relation load all associated documents in memory on save.

      If we update a document after, this will validate all documents associated.

      Here is a reduced testcase. The first business is validated 2 times instead of one.

      require "spec_helper"
      
      COUNT = {}
      
      class Business
        include Mongoid::Document
      
        field :test, type: String
      
        has_and_belongs_to_many :owners, autosave: true
      
        validate :count_validate
      
        def count_validate
          COUNT[self.id] ||= 0
          COUNT[self.id] += 1
          true
        end
      end
      
      class Owner
        include Mongoid::Document
      
        has_and_belongs_to_many :business, autosave: true
      end
      
      describe Business do
        let(:owner) { Owner.create }
        let(:business1) { Business.create }
        let(:business2) { Business.create }
      
        it "dont validate other business when adding an owner" do
          business1.owners << owner
      
          owner2 = Owner.find(owner.id)
          business2.owners << owner2
      
          expect(COUNT[business1.id]).to eql(1)
          expect(COUNT[business2.id]).to eql(1)
      
          business2.test = 'test'
          business2.save
      
          expect(COUNT[business1.id]).to eql(1)
          expect(COUNT[business2.id]).to eql(2)
        end
      end
      

      The documentation state that the validation are only performed on the in-memory documents, so I didn't expected that.

      What do you think?

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            francois2metz francois2metz
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: