Skip to content

Commit 5ad14d1

Browse files
authored
Merge pull request rails#53769 from fatkodima/fix-destroy_async-for-polymorphic-belongs_to
Fix asynchronous destroying of polymorphic `belongs_to` associations
2 parents b88a532 + 1df1373 commit 5ad14d1

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

activerecord/lib/active_record/associations/belongs_to_association.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,16 @@ def handle_dependency
1919
id = owner.public_send(reflection.foreign_key)
2020
end
2121

22+
association_class = if reflection.polymorphic?
23+
owner.public_send(reflection.foreign_type)
24+
else
25+
reflection.klass
26+
end
27+
2228
enqueue_destroy_association(
2329
owner_model_name: owner.class.to_s,
2430
owner_id: owner.id,
25-
association_class: reflection.klass.to_s,
31+
association_class: association_class.to_s,
2632
association_ids: [id],
2733
association_primary_key_column: primary_key_column,
2834
ensuring_owner_was_method: options.fetch(:ensuring_owner_was, nil)

activerecord/test/activejob/destroy_association_async_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
require "models/essay_destroy_async"
77
require "models/tag"
88
require "models/tagging"
9+
require "models/author"
910
require "models/essay"
1011
require "models/category"
1112
require "models/post"
@@ -209,6 +210,20 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase
209210
DestroyAsyncParent.delete_all
210211
end
211212

213+
test "polymorphic belongs_to" do
214+
writer = Author.create(name: "David")
215+
essay = EssayDestroyAsync.create!(name: "Der be treasure", writer: writer)
216+
217+
essay.destroy
218+
219+
assert_difference -> { Author.count }, -1 do
220+
perform_enqueued_jobs only: ActiveRecord::DestroyAssociationAsyncJob
221+
end
222+
ensure
223+
EssayDestroyAsync.delete_all
224+
Author.delete_all
225+
end
226+
212227
test "has_one" do
213228
content = Content.create(title: "hello")
214229
book = BookDestroyAsync.create!(name: "Arr, matey!")

activerecord/test/models/essay_destroy_async.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
class EssayDestroyAsync < ActiveRecord::Base
44
self.table_name = "essays"
55
belongs_to :book, dependent: :destroy_async, class_name: "BookDestroyAsync"
6+
belongs_to :writer, primary_key: :name, polymorphic: true, dependent: :destroy_async
67
end
78

89
class LongEssayDestroyAsync < EssayDestroyAsync

0 commit comments

Comments
 (0)