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

`set` nilifies attributes excluded via `only`

    • Fully Compatible

      When fetching a document with only, attempting to set an excluded attribute persists that attribute as nil, e.g.:

      Person.create(name: "bob", age: 42)
      #=> #<Person _id: ..., name: "bob", age: 42>
      
      person = Person.only(:name).last
      #=> #<Person _id: ..., name: "bob", age: nil>
      
      person.set(age: 53)
      
      Person.last
      #=> #<Person _id: ..., name: "bob", age: nil>
      

      I would understand if the in-memory document doesn't get updated because of only(:name) but I would certainly expect a persisted age value of 53. After all, that's what set is supposed to do:

      Perform a $set operation on the provided field/value pairs and set the values in the document in memory.

      Having set(age: 53) result in an age value of nil seems plain wrong.

      BTW, calling set on the criteria object works as expected, e.g.:

      criteria = Person.where(name: 'bob').only(:name)
      #=> #<Mongoid::Criteria ...>
      
      criteria.set(age: 53)
      
      Person.last
      #=> #<Person _id: ..., name: "bob", age: 53>
      

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            mail@stefanschuessler.de Stefan Schüßler
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: