From d5bf649a535948e70692e521ce3070595334e71b Mon Sep 17 00:00:00 2001 From: Seb Jacobs Date: Thu, 15 Jan 2015 23:03:23 +0000 Subject: Add support for bidirectional destroy dependencies Prior to this commit if you defined a bidirectional relationship between two models with destroy dependencies on both sides, a call to `destroy` would result in an infinite callback loop. Take the following relationship. class Content < ActiveRecord::Base has_one :content_position, dependent: :destroy end class ContentPosition < ActiveRecord::Base belongs_to :content, dependent: :destroy end Calling `Content#destroy` or `ContentPosition#destroy` would result in an infinite callback loop. This commit changes the behaviour of `ActiveRecord::Callbacks#destroy` so that it guards against subsequent callbacks. Thanks to @zetter for demonstrating the issue with failing tests[1]. [1] rails#13609 --- activerecord/test/models/content.rb | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 activerecord/test/models/content.rb (limited to 'activerecord/test/models/content.rb') diff --git a/activerecord/test/models/content.rb b/activerecord/test/models/content.rb new file mode 100644 index 0000000000..140e1dfc78 --- /dev/null +++ b/activerecord/test/models/content.rb @@ -0,0 +1,40 @@ +class Content < ActiveRecord::Base + self.table_name = 'content' + has_one :content_position, dependent: :destroy + + def self.destroyed_ids + @destroyed_ids ||= [] + end + + before_destroy do |object| + Content.destroyed_ids << object.id + end +end + +class ContentWhichRequiresTwoDestroyCalls < ActiveRecord::Base + self.table_name = 'content' + has_one :content_position, foreign_key: 'content_id', dependent: :destroy + + after_initialize do + @destroy_count = 0 + end + + before_destroy do + @destroy_count += 1 + if @destroy_count == 1 + throw :abort + end + end +end + +class ContentPosition < ActiveRecord::Base + belongs_to :content, dependent: :destroy + + def self.destroyed_ids + @destroyed_ids ||= [] + end + + before_destroy do |object| + ContentPosition.destroyed_ids << object.id + end +end -- cgit v1.2.3