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

after_destroy: parent is nil when embedded child is destroyed via nested attributes

    • Type: Icon: Task Task
    • Resolution: Done
    • 2.5.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      Very similar to MONGOID-1154 except it only seems to happen when the embedded document is destroyed via nested attributes.

      class Order
        
        include Mongoid::Document
        
        embeds_many :line_items, :cascade_callbacks => true
        
        accepts_nested_attributes_for :line_items, :allow_destroy => true
      
        def recalculate_discounts!
          # do stuff
        end
      
      end
      
      class LineItem
      
        include Mongoid::Document
      
        embedded_in :order
      
      end
      
      class LineItemObserver < Mongoid::Observer
        
        def after_destroy(line_item)
          line_item.order.recalculate_discounts!
        end
      
      end
      

      Everything works as expected when I call destroy directly on the line_item in rails console:

      order = Order.last
      line_item = order.line_items.first
      line_item.destroy

      1. => after_destroy is triggered and recalculate_discounts! is successfully called

      However when I try to destroy the embedded document via nested attributes (_destroy = "1"), the callback is triggered but the order object is nil:

      order = Order.last
      order.attributes = {:_id => '4fe257701defe75606000001',:line_items_attributes => [{:_id => '4fe268771defe79807000001',:_destroy => "1"}]}
      order.save

      1. => undefined method `recalculate_discounts!' for nil:NilClass

      Is this intended behaviour or a bug?

      I get the same result in Mongoid 2.4.10, 2.4.11 and 3.0.0.rc

            Assignee:
            durran Durran Jordan
            Reporter:
            russellbrown russellbrown
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: