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

Improve callback behavior in transactions

    • Type: Icon: Improvement Improvement
    • Resolution: Duplicate
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: None
    • None

      Problem Statement

      Based on this example from Rails: https://guides.rubyonrails.org/active_record_callbacks.html#transaction-callbacks
       

      class Picture < ApplicationRecord
        after_commit :delete_picture_file_from_disk, on: :destroy
      
        def delete_picture_file_from_disk
          File.delete(filepath) if File.exist?(filepath)
        end
      end
      

      This callback will only be triggered if the Picture object is deleted within a transaction.

      If you add an additional after_destroy callback, then destroying within a transaction will trigger the delete_picture_file_from_disk method twice: once when destroy is called, and once again on commit. A further problem is that, if the transaction is rolled back, then the after_destroy would have still been called.

      What makes the most sense for users is to have a callback method that is guaranteed to trigger only once immediately after the persistence action has happened, either on commit (if transaction) or else after a normal op (if non-transaction).

      Proposed Solutions

      Possible solutions could be:
      1. Introduce a new after_persistence callback, which has the behavior described above.
      2. Alter the behavior of the existing callbacks after_commit and/or after_save. This is probably undesirable as it would create divergence from Rails.

            Assignee:
            dmitry.rybakov@mongodb.com Dmitry Rybakov
            Reporter:
            shields@tablecheck.com Johnny Shields
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: