Merge pull request #51966 from fatkodima/exists-and-loaded

Optimize `ActiveRecord::Relation#exists?` with no conditions for loaded relations
This commit is contained in:
Jean Boussier 2024-06-01 10:26:22 +02:00 committed by GitHub
commit 0378b056de
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 0 deletions

@ -365,6 +365,7 @@ def exists?(conditions = :none)
end
return false if !conditions || limit_value == 0
return !records.empty? if conditions == :none && loaded?
if eager_loading?
relation = apply_join_dependency(eager_loading: false)

@ -285,6 +285,19 @@ def test_exists_returns_true_with_one_record_and_no_args
assert_equal true, Topic.exists?
end
def test_exists_with_loaded_relation
topics = Topic.all.load
assert_no_queries do
assert_equal true, topics.exists?
end
Topic.delete_all
topics = Topic.all.load
assert_no_queries do
assert_equal false, topics.exists?
end
end
def test_exists_returns_false_with_false_arg
assert_equal false, Topic.exists?(false)
end