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

Setting an embeds_many association to empty array does not persist it when a document is created

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Minor - P4 Minor - P4
    • 8.0.1
    • Affects Version/s: 7.1.0
    • Component/s: Associations, Persistence
    • Labels:
      None
    • Minor Change

      Test case: https://github.com/p-mongo/tests/blob/master/mongoid-app/lib/tasks/test_4868_2.rake

      If conditions is an embeds_many association on a contract, and I do:

      contract = Contract.new
      
      contract.conditions = []
      
      contract.save!
      

      ... the contract does not have a conditions field written to the database.

      If I write a non-empty array to conditions, and then set conditions to an empty array, it is persisted as expected:

      contract = Contract.new
      
      contract.conditions = [Condition.new]
      contract.save!
      
      contract.conditions = []
      contract.save!
      

      However, if the base model is unsaved, even setting conditions to a non-empty array prior to persistence is insufficient to force an empty array to be written out. The following does not write anything into conditions:

      contract = Contract.new
      
      contract.conditions = [Condition.new]
      contract.conditions = []
      
      contract.save!
      

      Note that Mongoid converts the missing attribute to an empty array, so as far as Mongoid application is concerned the conditions are still usable and have the right content. But the persisted data does not match what it should be (actual: missing value, expected: an empty array).

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: