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

Can't loop and delete embedded documents

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

      I have roughly the following:

      class Thing
        include Mongoid::Document
      
        embeds_many :links
      end
      
      class Link
        include Mongoid::Document
      
        embedded_in :thing
      
        def proper_destroy
          all_inverse_links.delete_all
          self.delete
        end
      
        # NOTE: may need to reload the other_thing to get the real links
        def all_inverse_links
          other_thing.links.where(inverse_link_criteria)
        end
      
        def inverse_link_criteria
          {'direction' => Link.opposite_direction(direction), 'rel_id' => rel_id, 'other_thing_id' => thing.id}
        end
      end
      

      I need to loop through the links of one thing, delete all inverse links, then delete the link itself.

      Basically what happens is the loop stops before it's done.

      I was informed callbacks could short circuit things, so I removed all Link callbacks, and used delete instead of destroy

      NOTE that even if i just outright delete the link without using my own methods - as in thing.links.each

      { | link | link.delete }

      it stops before it's done also

      Oh and I've tried reloading the thing, the links are still there.

      Here's it happening in the console:

      1.9.3p194 :002 > t.links.count
       => 12 
      1.9.3p194 :003 > t.links.each {|l| l.proper_destroy }
       => [#<Link _id: 50616b9d536bca610700005b, _type: nil, direction: -1, rel_id: "50616b9c536bca6107000029", other_thing_id: "50616b9d536bca6107000059">, #<Link _id: 50616b9e536bca6107000077, _type: nil, direction: -1, rel_id: "50616b9c536bca6107000029", other_thing_id: "50616b9e536bca6107000075">, #<Link _id: 50616b9f536bca6107000087, _type: nil, direction: -1, rel_id: "50616b9c536bca6107000029", other_thing_id: "50616b9f536bca6107000085">, #<Link _id: 50616ba0536bca6107000097, _type: nil, direction: -1, rel_id: "50616b9c536bca6107000029", other_thing_id: "50616ba0536bca6107000095">, #<Link _id: 50616ba1536bca61070000a7, _type: nil, direction: -1, rel_id: "50616b9c536bca6107000029", other_thing_id: "50616ba1536bca61070000a5">, #<Link _id: 50616ba2536bca61070000b7, _type: nil, direction: -1, rel_id: "50616b9c536bca6107000029", other_thing_id: "50616ba2536bca61070000b5">] 
      1.9.3p194 :004 > t.links.count
       => 6 
      

      Any ideas?

      Thanks

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

              Created:
              Updated:
              Resolved: