Skip to content

Commit 6cab674

Browse files
committed
Optimize ActiveRecord::Relation#exists? with no conditions for loaded relations
1 parent bc56661 commit 6cab674

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

activerecord/lib/active_record/relation/finder_methods.rb

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

367367
return false if !conditions || limit_value == 0
368+
return !records.empty? if conditions == :none && loaded?
368369

369370
if eager_loading?
370371
relation = apply_join_dependency(eager_loading: false)

activerecord/test/cases/finder_test.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,19 @@ def test_exists_returns_true_with_one_record_and_no_args
285285
assert_equal true, Topic.exists?
286286
end
287287

288+
def test_exists_with_loaded_relation
289+
topics = Topic.all.load
290+
assert_no_queries do
291+
assert_equal true, topics.exists?
292+
end
293+
294+
Topic.delete_all
295+
topics = Topic.all.load
296+
assert_no_queries do
297+
assert_equal false, topics.exists?
298+
end
299+
end
300+
288301
def test_exists_returns_false_with_false_arg
289302
assert_equal false, Topic.exists?(false)
290303
end

0 commit comments

Comments
 (0)