Skip to content

Commit

Permalink
Merge pull request rails#29855 from lugray/has_one_destroyed_by_assoc…
Browse files Browse the repository at this point in the history
…iation

Match destroyed_by_association for has_one to has_many
  • Loading branch information
rafaelfranca committed Jul 21, 2017
1 parent b6e24db commit 8254a8b
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
7 changes: 7 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,10 @@
* When a `has_one` association is destroyed by `dependent: destroy`,
`destroyed_by_association` will now be set to the reflection, matching the
behaviour of `has_many` associations.

*Lisa Ugray*


## Rails 5.1.3.rc1 (July 19, 2017) ##

* `Relation#joins` is no longer affected by the target model's
Expand Down
Expand Up @@ -56,6 +56,7 @@ def delete(method = options[:dependent])
when :delete
target.delete
when :destroy
target.destroyed_by_association = reflection
target.destroy
when :nullify
target.update_columns(reflection.foreign_key => nil) if target.persisted?
Expand All @@ -78,6 +79,7 @@ def remove_target!(method)
when :delete
target.delete
when :destroy
target.destroyed_by_association = reflection
target.destroy
else
nullify_owner_attributes(target)
Expand Down
34 changes: 34 additions & 0 deletions activerecord/test/cases/associations/has_one_associations_test.rb
Expand Up @@ -679,4 +679,38 @@ def test_association_enum_works_properly_with_nested_join
SpecialAuthor.joins(book: :subscription).where.not(where_clause)
end
end

class DestroyByParentBook < ActiveRecord::Base
self.table_name = "books"
belongs_to :author, class_name: "DestroyByParentAuthor"
before_destroy :dont, unless: :destroyed_by_association

def dont
throw(:abort)
end
end

class DestroyByParentAuthor < ActiveRecord::Base
self.table_name = "authors"
has_one :book, class_name: "DestroyByParentBook", foreign_key: "author_id", dependent: :destroy
end

test "destroyed_by_association set in child destroy callback on parent destroy" do
author = DestroyByParentAuthor.create!(name: "Test")
book = DestroyByParentBook.create!(author: author)

author.destroy

assert_not DestroyByParentBook.exists?(book.id)
end

test "destroyed_by_association set in child destroy callback on replace" do
author = DestroyByParentAuthor.create!(name: "Test")
book = DestroyByParentBook.create!(author: author)

author.book = DestroyByParentBook.create!
author.save!

assert_not DestroyByParentBook.exists?(book.id)
end
end

0 comments on commit 8254a8b

Please sign in to comment.