Skip to content

Commit

Permalink
Merge pull request rails#29593 from kratob/master
Browse files Browse the repository at this point in the history
ActiveRecord: do not create "has many through" records that have been removed
  • Loading branch information
eileencodes authored and rafaelfranca committed Jun 28, 2017
1 parent 5aa510e commit a22c39e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
8 changes: 8 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,11 @@
* Previously, when building records using a `has_many :through` association,
if the child records were deleted before the parent was saved, they would
still be persisted. Now, if child records are deleted before the parent is saved
on a `has_many :through` association, the child records will not be persisted.

*Tobias Kraze*


## Rails 5.1.2 (June 26, 2017) ##

* Restore previous behavior of collection proxies: their values can have
Expand Down
Expand Up @@ -109,6 +109,11 @@ def build_record(attributes)
record
end

def remove_records(existing_records, records, method)
super
delete_through_records(records)
end

def target_reflection_has_associated_record?
!(through_reflection.belongs_to? && owner[through_reflection.foreign_key].blank?)
end
Expand Down
Expand Up @@ -337,6 +337,17 @@ def test_build_then_save_with_has_one_inverse
assert_includes post.single_people, person
end

def test_build_then_remove_then_save
post = posts(:thinking)
post.people.build(first_name: "Bob")
ted = post.people.build(first_name: "Ted")
post.people.delete(ted)
post.save!
post.reload

assert_equal ["Bob"], post.people.collect(&:first_name)
end

def test_both_parent_ids_set_when_saving_new
post = Post.new(title: "Hello", body: "world")
person = Person.new(first_name: "Sean")
Expand Down

0 comments on commit a22c39e

Please sign in to comment.