Skip to content

Commit 362fbd2

Browse files
authored
Merge pull request rails#52151 from fatkodima/exists-with-updated-records
Fix `ActiveRecord::Relation#exists?` with no conditions for loaded relations and updated records
2 parents b06c2c7 + 5dd2da7 commit 362fbd2

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

activerecord/lib/active_record/relation/finder_methods.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,12 @@ def exists?(conditions = :none)
365365
end
366366

367367
return false if !conditions || limit_value == 0
368-
return records.any?(&:persisted?) if conditions == :none && loaded?
368+
369+
# Ignore if we have records which have saved changes since the load, because the
370+
# relation can be a CollectionProxy and we updated the reference to the owner record.
371+
if conditions == :none && loaded? && records.none?(&:saved_changes?)
372+
return records.any?(&:persisted?)
373+
end
369374

370375
if eager_loading?
371376
relation = apply_join_dependency(eager_loading: false)

activerecord/test/cases/finder_test.rb

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,23 @@ def test_exists_with_loaded_relation_having_unsaved_records
310310
assert_not_empty posts
311311
posts.each(&:destroy)
312312

313-
assert_not_predicate posts, :exists?
313+
assert_no_queries do
314+
assert_not_predicate posts, :exists?
315+
end
316+
end
317+
318+
def test_exists_with_loaded_relation_having_updated_owner_record
319+
author = authors(:david)
320+
assert_not_empty author.posts
321+
322+
author.posts.each do |post|
323+
post.author = nil
324+
post.save!
325+
end
326+
327+
assert_queries_count(1) do
328+
assert_not_predicate author.posts, :exists?
329+
end
314330
end
315331

316332
# exists? should handle nil for id's that come from URLs and always return false

0 commit comments

Comments
 (0)