audited icon indicating copy to clipboard operation
audited copied to clipboard

Skipping create audit leads to bad data

Open mcyoung opened this issue 1 year ago • 0 comments

If you skip the create audit you might get inaccurate data with revisions. For example, if you have a User model w/ first_name, middle_name, last_name attributes, include audited w/o create via audited on: %I[update destroy] and you create a new user via:

u = User.create!(first_name: "John", last_name: "Doe")

calling

u.audits # => []

which is expected.

However, if you make a couple updates, you'll start to see the revision data fall apart, e.g.

u.update!(last_name: "Dooooooeeee")
u.revisions

returns expected results:

[
    [0] #<User:0x0000000106ff9928> {
                 :id => 2,
         :first_name => "John",
          :last_name => "Dooooooeeee",
        :middle_name => nil,
         :created_at => nil,
         :updated_at => nil
    }
]

notice the middle_name for this singular revision is still nil. Things get interesting if you now update that middle_name attribute and run revisions again:

u.update!(middle_name: "F")
u.revisions

notice that the middle_name for both revisions now incorrectly shows "F" as the value. This shouldn't be the case for the 1st revision as it was still nil as shown above.

[
    [0] #<User:0x000000010706a8d0> {
                 :id => 2,
         :first_name => "John",
          :last_name => "Dooooooeeee",
        :middle_name => "F",
         :created_at => nil,
         :updated_at => nil
    },
    [1] #<User:0x0000000107069548> {
                 :id => 2,
         :first_name => "John",
          :last_name => "Dooooooeeee",
        :middle_name => "F",
         :created_at => nil,
         :updated_at => nil
    }
]

mcyoung avatar Aug 22 '23 01:08 mcyoung