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

Weird inconsistency when setting embedded relation from same row

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

      So maybe I shouldn't be doing this in this first place, but just trust me when I say that my application sorta depends on it. I have a 1..N embedded relation in a totally blank rails 3.0.9 project with mongoid master. I've also tested mongoid 2.0.0..2 and this behavior persists.

      Basically I want to make a change on a property of an embedded doc and then use relation= to set the relation on another instance of the model which points to the same row. This actually works, except if I have called #count (or any other of several methods which seem to change the internal state of the relation) on the relation of the second instance.

      This is the one that does not work as #count is called:

      > p = Product.create
      => #<Product _id: 4e150eed2abea92041000001, _type: nil> 
      
      # create a subdoc
      > p.variations.create(name: 'one')
      => #<Variation name: "one"> 
      
      # get another instance of the same product
      > pb = Product.last
      => #<Product _id: 4e150eed2abea92041000001> 
      
      # set a property of a subdoc
      > p.variations.first.name = 'two'
      => "two" 
      
      # call #count on the relation, this is what breaks it (!)
      > pb.variations.count
      => 1 
      
      # set the relation directly
      > pb.variations = p.variations
      => [] 
      
      # broken
      > Product.last.variations
      => [] 
      

      This version works totally as expected because no such call is made:

      > p = Product.create
      => #<Product _id: 4e150eb82abea92035000001> 
      
      # create a subdoc
      > p.variations.create(name: 'one')
      => #<Variation name: "one"> 
      
      # get another instance of the same product
      > pb = Product.last
      => #<Product _id: 4e150eb82abea92035000001> 
      
      # set a property on a subdoc
      > p.variations.first.name = 'two'
      => "two" 
      
      # set the relation from itself
      > pb.variations = p.variations
      => [#<Variation name: "two">] 
      
      # as expected
      > Product.last.variations
      => [#<Variation name: "two">] 
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            lyleunderwood lyleunderwood
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: