Skip to content

Commit ea8d186

Browse files
committed
Add suggestions for checking if collection is empty
1 parent b14b217 commit ea8d186

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

README.adoc

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1069,6 +1069,25 @@ User.all.size
10691069
User.all.length
10701070
----
10711071

1072+
=== Check if the collection is empty [[check-empty-collection]]
1073+
1074+
When checking if the unloaded Active Record collection is empty, prefer `any?`/`empty?` over `present?`/`blank?`. The former executes a simple `EXISTS`-like query while the latter loads the whole collection to determine it's size.
1075+
1076+
[source,ruby]
1077+
----
1078+
# bad
1079+
users.where(active: true).present?
1080+
users.where(active: true).blank?
1081+
1082+
# good
1083+
users.where(active: true).any?
1084+
users.where(active: true).empty?
1085+
1086+
# good - the collection is used after loading
1087+
users.present?
1088+
users.each(&:notify)
1089+
----
1090+
10721091
=== Where with Ranges [[where-ranges]]
10731092

10741093
Use ranges instead of defining comparative conditions using a template for scalar values.

0 commit comments

Comments
 (0)