Skip to content

Commit a6c27d5

Browse files
authored
Merge pull request rails#38990 from eugeneius/transaction_callbacks_object_id
Use __id__ to dedup records for transactional callbacks
2 parents 0fac455 + 8d3ca97 commit a6c27d5

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

activerecord/lib/active_record/connection_adapters/abstract/transaction.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def materialized?
101101

102102
def rollback_records
103103
return unless records
104-
ite = records.uniq(&:object_id)
104+
ite = records.uniq(&:__id__)
105105
already_run_callbacks = {}
106106
while record = ite.shift
107107
trigger_callbacks = record.trigger_transactional_callbacks?
@@ -121,7 +121,7 @@ def before_commit_records
121121

122122
def commit_records
123123
return unless records
124-
ite = records.uniq(&:object_id)
124+
ite = records.uniq(&:__id__)
125125
already_run_callbacks = {}
126126
while record = ite.shift
127127
if @run_commit_callbacks

activerecord/test/cases/transaction_callbacks_test.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,43 @@ def test_saving_a_record_with_a_belongs_to_that_specifies_touching_the_parent_sh
501501
assert flag
502502
end
503503

504+
def test_saving_two_records_that_override_object_id_should_run_after_commit_callbacks_for_both
505+
klass = Class.new(TopicWithCallbacks) do
506+
define_method(:object_id) { 42 }
507+
end
508+
509+
records = [klass.new, klass.new]
510+
511+
klass.transaction do
512+
records.each do |record|
513+
record.after_commit_block { |r| r.history << :after_commit }
514+
record.save!
515+
end
516+
end
517+
518+
assert_equal [:after_commit], records.first.history
519+
assert_equal [:after_commit], records.second.history
520+
end
521+
522+
def test_saving_two_records_that_override_object_id_should_run_after_rollback_callbacks_for_both
523+
klass = Class.new(TopicWithCallbacks) do
524+
define_method(:object_id) { 42 }
525+
end
526+
527+
records = [klass.new, klass.new]
528+
529+
klass.transaction do
530+
records.each do |record|
531+
record.after_rollback_block { |r| r.history << :after_rollback }
532+
record.save!
533+
end
534+
raise ActiveRecord::Rollback
535+
end
536+
537+
assert_equal [:after_rollback], records.first.history
538+
assert_equal [:after_rollback], records.second.history
539+
end
540+
504541
private
505542
def add_transaction_execution_blocks(record)
506543
record.after_commit_block(:create) { |r| r.history << :commit_on_create }

0 commit comments

Comments
 (0)