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

Model.only => update_attribute changing unmodified attributes

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

      I'm not sure if this is intended behavior or not.

      class User
        include Mongoid::Document
        include Mongoid::Timestamps
        field :name
        field :is_admin, type: Boolean, default: false
        belongs_to :relation
      end
      
      User.create(name: 'bob', :is_admin => true)
      user = User.only(:id, :relation_id).where(name: 'bob').first
      user.update_attribute(:relation_id, some_id) #only expect relation_id and updated_at to be changed
      

      Yields an update along the lines of:

      MONGODB db['users'].update(

      {"_id"=>BSON::ObjectId('4efcc972a393a97fb300080c')}

      , {"$set"=>{"is_admin"=>false, "relation_id"=>BSON::ObjectId('4efce81fa393a9823b000001'), "updated_at"=>2012-01-31 16:18:39 UTC}})

      As you can see it is setting is_admin back to the default value (false) instead of leaving it alone even though it was not actually "changed". I can see why this might happen since the User loaded with only(:id, :relation_id) has no value set for is_admin but to me this is unexpected behavior. I would expect for an existing model it would set the dirty flag on an attribute only if that field is actually modified after the model is loaded.

      P.S. In this bogus scenario above 'only' would not really be needed but in my actual use-case I'm going through lots of documents and trying to minimize memory usage by not fetching unnecessary fields. Is there some other way to force mongoid to ONLY update a single field and ignore its normal behavior?

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

              Created:
              Updated:
              Resolved: