File tree Expand file tree Collapse file tree 3 files changed +31
-0
lines changed
lib/active_record/relation Expand file tree Collapse file tree 3 files changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ * Optimize ` Relation#exists? ` when records are loaded and the relation has no conditions.
2
+
3
+ This can avoid queries in some cases.
4
+
5
+ * fatkodima*
6
+
1
7
* Add a ` filter ` option to ` in_order_of ` to prioritize certain values in the sorting without filtering the results
2
8
by these values.
3
9
Original file line number Diff line number Diff line change @@ -365,6 +365,7 @@ def exists?(conditions = :none)
365
365
end
366
366
367
367
return false if !conditions || limit_value == 0
368
+ return records . any? ( &:persisted? ) if conditions == :none && loaded?
368
369
369
370
if eager_loading?
370
371
relation = apply_join_dependency ( eager_loading : false )
Original file line number Diff line number Diff line change @@ -289,6 +289,30 @@ def test_exists_returns_false_with_false_arg
289
289
assert_equal false , Topic . exists? ( false )
290
290
end
291
291
292
+ def test_exists_with_loaded_relation
293
+ topics = Topic . all . load
294
+ assert_no_queries do
295
+ assert_predicate topics , :exists?
296
+ end
297
+ end
298
+
299
+ def test_exists_with_empty_loaded_relation
300
+ Topic . delete_all
301
+ topics = Topic . all . load
302
+ assert_no_queries do
303
+ assert_not_predicate topics , :exists?
304
+ end
305
+ end
306
+
307
+ def test_exists_with_loaded_relation_having_unsaved_records
308
+ author = authors ( :david )
309
+ posts = author . posts . load
310
+ assert_not_empty posts
311
+ posts . each ( &:destroy )
312
+
313
+ assert_not_predicate posts , :exists?
314
+ end
315
+
292
316
# exists? should handle nil for id's that come from URLs and always return false
293
317
# (example: Topic.exists?(params[:id])) where params[:id] is nil
294
318
def test_exists_with_nil_arg
You can’t perform that action at this time.
0 commit comments