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

update_attributes does not persist correctly on embedded subcollection

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

      Calling update_attributes on an embedded document, where one of the hash members is itself a second embedded document, produces an incorrect mongo query and as a result fails to persist the nested document.

      For example, using these documents:

      Person
      embeds_many Addresses

      Address
      embedded_in Person
      embeds_many Locations

      Location
      embedded_in Address

      With this pseudo-code:

      p = Person.create( name: "Jimmy", addresses: [ { city: 'Buffalo', locations: [

      { name: 'Work' }

      ] } ] )

      attributes = { city: 'New York', locations: [

      { name: 'Home' }

      ] }
      p.addresses.first.update_attributes( attributes )

      puts "#

      {p.addresses.first.city}

      " # Prints "New York", as expected
      puts "#

      {p.addresses.first.locations.first.name}

      " # Prints "Home", as expected

      new_p = p.reload
      puts "#

      {new_p.addresses.first.locations.first.name}

      " # Prints "Work" – wrong

      The third line prints the old value ("Work"). Observing the Mongo driver, this query is emitted:

      MONGODB (0ms) mongoid_test['people'].update(

      {"_id"=>BSON::ObjectId('4f7380bb51e63a588000009a'), "addresses._id"=>"tauentzienstr"}

      , {"$set"=>{"addresses.0.city"=>"Berlin", "locations"=>[

      {"_id"=>BSON::ObjectId('4f7380bb51e63a588000009b'), "name"=>"Home"}

      ]}})

      If this weren't weird enough, inspecting the document after running the above code shows that the "locations" collection has been added to the people document, where it contains the correct values:

      puts "#

      {new_p['locations']}

      " # Should be nil, but prints out the locations array

      I've written some specs that test for this bug and will send a pull request for them shortly.

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

              Created:
              Updated:
              Resolved: