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

Indifferent access into hashes nested in array field does not work before persistence

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 9.0.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:
    • Minor Change

      When a field of type Array is declared, and a value is assigned to it, and the value is an array of hashes, the inner hashes of the value are retained as is in the model's attributes. If the hashes are genuine Hash instances (not BSON::Document or AS::HashWithIndifferentAccess), these hash instances are not indifferently accessible.

      Upon persistence and load from database, the same data becomes an array of BSON::Document instances which are indifferently accessible.

      I think Mongoid should make the hashes indifferently accessible by converting them into BSON::Document instances upon assignment, so that access of components of attributes works the same before and after persistence.

      class Bar
        include Mongoid::Document
        
        field :a, type: Array
        field :h, type: Hash
      end
      
      bar = Bar.new(a: [{foo: 42}])
      # 42
      p bar.a.first[:foo]
      # nil
      p bar.a.first['foo']
      
      bar.save!
      bar.reload
      
      # 42
      p bar.a.first[:foo]
      # 42
      p bar.a.first['foo']
      

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

              Created:
              Updated:
              Resolved: