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

attribute_was returns previous value in after_save callback

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Critical - P2 Critical - P2
    • 8.0.1
    • Affects Version/s: None
    • Component/s: Attributes
    • None

      ActiveRecord updates the existing attribute values to the new ones prior to after_save callback being called:

      class Cat < ApplicationRecord
        after_save do
          p self
          p attribute_was(:age)
        end
      end
      
      irb(main):009:0> cat = Cat.first
        Cat Load (0.4ms)  SELECT "cats".* FROM "cats" ORDER BY "cats"."id" ASC LIMIT ?  [["LIMIT", 1]]
      => #<Cat id: 1, created_at: "2021-05-27 01:07:51.110557000 +0000", updated_at: "2021-05-27 01...
      irb(main):010:0> cat.age=5
      => 5
      irb(main):011:0> cat.save!
        TRANSACTION (0.2ms)  begin transaction
        Cat Update (0.5ms)  UPDATE "cats" SET "updated_at" = ?, "age" = ? WHERE "cats"."id" = ?  [["updated_at", "2021-05-27 01:08:29.723938"], ["age", 5], ["id", 1]]
      #<Cat id: 1, created_at: "2021-05-27 01:07:51.110557000 +0000", updated_at: "2021-05-27 01:08:29.723938000 +0000", age: 5>
      5
        TRANSACTION (4.7ms)  commit transaction
      => true
      
      

      Mongoid does not and continues to return the previous value:

      class Cat
        include Mongoid::Document
      
        field :age, type: Integer
      
        after_save do
          p self
          p attribute_was(:age)
        end
      end
      
      
      irb(main):001:0> a=Cat.create!
      #<Cat _id: 60aef1652c97a617438dc9bb, age: nil>
      nil
      => #<Cat _id: 60aef1652c97a617438dc9bb, age: nil>
      irb(main):002:0> a.age=2
      => 2
      irb(main):003:0> a.save!
      #<Cat _id: 60aef1652c97a617438dc9bb, age: 2>
      nil
      => true
      
      
      

            Assignee:
            dmitry.rybakov@mongodb.com Dmitry Rybakov
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: