Skip to content

Commit 4d5aed9

Browse files
committed
Do not consolidate persisted in-memory records
`merge_target_lists` is called with two arguments. A collection of persisted records and a collection of in-memory records. If the in-memory collection contains any persisted records we can safely reject them as the `persisted` collection is already up-to-date.
1 parent 57fe7df commit 4d5aed9

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Ignore persisted in-memory records when merging target lists.
2+
3+
*Kevin Sjöberg*
4+
15
* Add nested_attributes_for support for `delegated_type`
26

37
```ruby

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ def merge_target_lists(persisted, memory)
335335
end
336336
end
337337

338-
persisted + memory
338+
persisted + memory.reject(&:persisted?)
339339
end
340340

341341
def _create_record(attributes, raise = false, &block)

activerecord/test/cases/associations_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,16 @@ def test_reset_unloads_target
289289
assert_not_predicate david.posts, :loaded?
290290
assert_not_predicate david.posts, :loaded
291291
end
292+
293+
def test_target_merging_ignores_persisted_in_memory_records
294+
david = authors(:david)
295+
assert david.thinking_posts.include?(posts(:thinking))
296+
297+
david.thinking_posts.create!(title: "Something else entirely", body: "Does not matter.")
298+
299+
assert_equal 1, david.thinking_posts.size
300+
assert_equal 1, david.thinking_posts.to_a.size
301+
end
292302
end
293303

294304
class OverridingAssociationsTest < ActiveRecord::TestCase

0 commit comments

Comments
 (0)