Fix ActiveRecord::Relation#exists? with no conditions for loaded relations and updated records

This commit is contained in:
fatkodima 2024-06-19 12:15:20 +03:00
parent 869c7bf094
commit 5dd2da7ee8
2 changed files with 23 additions and 2 deletions

@ -365,7 +365,12 @@ def exists?(conditions = :none)
end
return false if !conditions || limit_value == 0
return records.any?(&:persisted?) if conditions == :none && loaded?
# Ignore if we have records which have saved changes since the load, because the
# relation can be a CollectionProxy and we updated the reference to the owner record.
if conditions == :none && loaded? && records.none?(&:saved_changes?)
return records.any?(&:persisted?)
end
if eager_loading?
relation = apply_join_dependency(eager_loading: false)

@ -310,8 +310,24 @@ def test_exists_with_loaded_relation_having_unsaved_records
assert_not_empty posts
posts.each(&:destroy)
assert_no_queries do
assert_not_predicate posts, :exists?
end
end
def test_exists_with_loaded_relation_having_updated_owner_record
author = authors(:david)
assert_not_empty author.posts
author.posts.each do |post|
post.author = nil
post.save!
end
assert_queries_count(1) do
assert_not_predicate author.posts, :exists?
end
end
# exists? should handle nil for id's that come from URLs and always return false
# (example: Topic.exists?(params[:id])) where params[:id] is nil