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

Parent ID missing in after_destroy callback when removing via nested attribute

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 8.0.1
    • Affects Version/s: None
    • Component/s: Persistence
    • Labels:
      None
    • Minor Change

      I'm experiencing issues similar to MONGOID-2127, where when deleting a child via nested attributes, in the child's after_destroy callback, the parent id is nil.

      Code to reproduce:

      class Parent
        include Mongoid::Document
        has_many :children
        accepts_nested_attributes_for :children, allow_destroy: true
      end
      class Child
        include Mongoid::Document
        belongs_to :parent
        after_destroy :do_something_related_to_parent
        
        private
      
        def do_something_related_to_parent
          puts self.attributes # parent_id is nil
          parent.children # undefined method `children' for nil:NilClass
        end
      end
      
      p = Parent.create
      c = p.children.create
      p.attributes = { '_id': p.id, 'children_attributes': [{ '_id': c.id, '_destroy': 1 }]}
      

      Output:

      {"_id"=>BSON::ObjectId('60cc6ad5495bdb945bf61924'), "parent_id"=>nil}
      Traceback (most recent call last):
              2: from (irb):25
              1: from (irb):15:in `do_something_related_to_parent'
      NoMethodError (undefined method `children' for nil:NilClass)
      

      When deleting children directly, the parent ID is present in the after_destroy callback, it's only when deleting via parent nested attribute that the parent ID is missing.

      This seems to happen on both 7.1.1 and 7.3.0 (haven't tested other versions)

       

       

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            robin.ginter@rangeforce.com Robin Ginter
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: