Optimize ActiveRecord::Relation#exists? with no conditions for loaded relations

This commit is contained in:
fatkodima 2024-05-31 14:04:34 +03:00
parent bc56661a3d
commit 6cab6744e8
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