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

Updating an association value to object instance when the instance has multiple inverses changes the wrong field

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 7.0.2
    • Component/s: None
    • None
    • Environment:
      Rails 5.2.2, Ruby 2.5.3

      Using the minimal example

      # app/models/address.rb
      class Address
        include Mongoid::Document
      
        field :city, type: String
      
        embedded_in :addressable, polymorphic: true
      end
      
      # app/models/company.rb
      class Company
        include Mongoid::Document
      
        embeds_one :address, class_name: 'Address', as: :addressable
        accepts_nested_attributes_for :address
      
        embeds_one :delivery_address, class_name: 'Address', as: :addressable
        accepts_nested_attributes_for :delivery_address
      end
      

      I can create and update Company records as expected when using attribute hashes

      2.5.3 :001 > acme = Company.create(address: { city: 'Gotham' }, delivery_address: { city: 'Parcelville' })
       => #<Company _id: 5cd32489a8f843353860cc0b, > 
      2.5.3 :002 > acme.reload.address.city
       => "Gotham" 
      2.5.3 :003 > acme.reload.delivery_address.city
       => "Parcelville" 
      2.5.3 :004 > acme.update(delivery_address: { city: 'Smallville' })
       => true 
      2.5.3 :005 > acme.reload.address.city
       => "Gotham" 
      2.5.3 :006 > acme.reload.delivery_address.city
       => "Smallville"
      

      but when I use an Address object as value, unexpected things happen:

      2.5.3 :007 > acme.update(delivery_address: Address.new(city: 'Bigville'))
       => true 
      2.5.3 :008 > acme.reload.address.city
       => "Bigville" # <-- delivery_address should have been updated, not address
      2.5.3 :009 > acme.reload.delivery_address.city
       => "Smallville" # <-- delivery_address unchanged despite call to #update
      

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            larnold@givve.com Leo Arnold
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: