Merge pull request #51987 from fatkodima/exists-and-loaded2
Optimize `ActiveRecord::Relation#exists?` with no conditions for loaded relations
This commit is contained in:
commit
c9075e3643
@ -1,3 +1,9 @@
|
||||
* Optimize `Relation#exists?` when records are loaded and the relation has no conditions.
|
||||
|
||||
This can avoid queries in some cases.
|
||||
|
||||
*fatkodima*
|
||||
|
||||
* Add a `filter` option to `in_order_of` to prioritize certain values in the sorting without filtering the results
|
||||
by these values.
|
||||
|
||||
|
@ -365,6 +365,7 @@ def exists?(conditions = :none)
|
||||
end
|
||||
|
||||
return false if !conditions || limit_value == 0
|
||||
return records.any?(&:persisted?) if conditions == :none && loaded?
|
||||
|
||||
if eager_loading?
|
||||
relation = apply_join_dependency(eager_loading: false)
|
||||
|
@ -289,6 +289,30 @@ def test_exists_returns_false_with_false_arg
|
||||
assert_equal false, Topic.exists?(false)
|
||||
end
|
||||
|
||||
def test_exists_with_loaded_relation
|
||||
topics = Topic.all.load
|
||||
assert_no_queries do
|
||||
assert_predicate topics, :exists?
|
||||
end
|
||||
end
|
||||
|
||||
def test_exists_with_empty_loaded_relation
|
||||
Topic.delete_all
|
||||
topics = Topic.all.load
|
||||
assert_no_queries do
|
||||
assert_not_predicate topics, :exists?
|
||||
end
|
||||
end
|
||||
|
||||
def test_exists_with_loaded_relation_having_unsaved_records
|
||||
author = authors(:david)
|
||||
posts = author.posts.load
|
||||
assert_not_empty posts
|
||||
posts.each(&:destroy)
|
||||
|
||||
assert_not_predicate posts, :exists?
|
||||
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
|
||||
def test_exists_with_nil_arg
|
||||
|
Loading…
Reference in New Issue
Block a user