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

Clarify/improve order of callback invocation on embedded associations vs host documents

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 8.0.1
    • Affects Version/s: None
    • Component/s: Associations, Callbacks
    • None

      I have a following setup:

      class Album
        
        include Mongoid::Document
        include Mongoid::Timestamps
      
        embeds_many :photos, cascade_callbacks: true
      
      end
      
      
      class Photo 
      
        include Mongoid::Document
      
        embedded_in :album
      
        mount_uploader :file, PhotoUploader
      
        after_save do
          PhotoWorker.perform_async(id)
        end
      
      end
      

      .. now, because I need to process photos with some Sidekiq workers I have an after_save callback (in Photo) that starts the worker.

      album.save
      

      However, the issue is that if the .save is called on the parent model, the embedded documents callbacks will all be called first, and the very 'save' command (for mongoid) will be sent only afterwards in the usual flow of parent document.

      I have some debug prints setup and it can be seen that the callbacks run as follows

      "photo before_save"
      "photo after_save"
      "album before_save"
      # runs the save call
      "album after_save"
      

      .. so you can see that in this case one is being told that a document has been saved when it is not, and so, in some cases, Sidekiq workers cannot find the documents.

      I'm guessing that this might not be the intended behaviour.

            Assignee:
            dmitry.rybakov@mongodb.com Dmitry Rybakov
            Reporter:
            mirzali mirzali
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: