rails icon indicating copy to clipboard operation
rails copied to clipboard

`previous_changes` overwritten upon multiple saves with a transaction block

Open vaidarnav opened this issue 2 months ago • 0 comments

Problem

More of a feature request: previous_changes gets overwritten every time an ActiveRecord is saved. This means that if a record is saved multiple times in a transaction block, upon committing there might be fields changes persisted upon committing that are not included in previous_changes.

This becomes a problem if we are relying on previous_changes to conditionally execute code in an after_commit. Anecdotally this has lead to silent skipping of execution in some important after_commits because of this non-obvious behavior.

This has been discussed before but the issue link is broken. Im very curious what was discussed

Request

either

  • change previous_changes implementation to accumulate changes over multiple saves in the lifecycle of the AR instance
  • add a method like previous_changes that does this

Steps to reproduce

class User < ActiveRecord::Base
  t.string : first_name
  t.string : last_name
end

# init record
user = User.new(first_name: 'Jeff', last_name: 'Bezos')
user.save! 

ApplicationRecord.transaction do
  employee.first_name = 'Bill'
  employee.save! # same behavior for update!
  employee.last_name = 'Gates'
  employee.save!
end

# expected previous_changes.keys --> ["first_name", "last_name"]
print(employee.previous_changes.keys) # actual output --> ["last_name"]

System configuration

Rails version: 7.0.8.1

Ruby version: 3.3.0

vaidarnav avatar Feb 25 '24 04:02 vaidarnav