Skip to content

Commit

Permalink
Merge pull request #53769 from fatkodima/fix-destroy_async-for-polymo…
Browse files Browse the repository at this point in the history
…rphic-belongs_to

Fix asynchronous destroying of polymorphic `belongs_to` associations
  • Loading branch information
kamipo authored Nov 28, 2024
2 parents b88a532 + 1df1373 commit 5ad14d1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,16 @@ def handle_dependency
id = owner.public_send(reflection.foreign_key)
end

association_class = if reflection.polymorphic?
owner.public_send(reflection.foreign_type)
else
reflection.klass
end

enqueue_destroy_association(
owner_model_name: owner.class.to_s,
owner_id: owner.id,
association_class: reflection.klass.to_s,
association_class: association_class.to_s,
association_ids: [id],
association_primary_key_column: primary_key_column,
ensuring_owner_was_method: options.fetch(:ensuring_owner_was, nil)
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/activejob/destroy_association_async_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
require "models/essay_destroy_async"
require "models/tag"
require "models/tagging"
require "models/author"
require "models/essay"
require "models/category"
require "models/post"
Expand Down Expand Up @@ -209,6 +210,20 @@ class DestroyAssociationAsyncTest < ActiveRecord::TestCase
DestroyAsyncParent.delete_all
end

test "polymorphic belongs_to" do
writer = Author.create(name: "David")
essay = EssayDestroyAsync.create!(name: "Der be treasure", writer: writer)

essay.destroy

assert_difference -> { Author.count }, -1 do
perform_enqueued_jobs only: ActiveRecord::DestroyAssociationAsyncJob
end
ensure
EssayDestroyAsync.delete_all
Author.delete_all
end

test "has_one" do
content = Content.create(title: "hello")
book = BookDestroyAsync.create!(name: "Arr, matey!")
Expand Down
1 change: 1 addition & 0 deletions activerecord/test/models/essay_destroy_async.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
class EssayDestroyAsync < ActiveRecord::Base
self.table_name = "essays"
belongs_to :book, dependent: :destroy_async, class_name: "BookDestroyAsync"
belongs_to :writer, primary_key: :name, polymorphic: true, dependent: :destroy_async
end

class LongEssayDestroyAsync < EssayDestroyAsync
Expand Down

0 comments on commit 5ad14d1

Please sign in to comment.