Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1069,6 +1069,25 @@ User.all.size
User.all.length
----

=== Check if the collection is empty [[check-empty-collection]]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is generic. The guideline is specific to "not loaded collection".
It is hard to know if it's loaded or not if it e.g. comes as an argument to a method, or elsewhere:

def highlight?
  recent_articles.any?
end


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 its size.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is even more descriptive.
user.articles.any? is used just as frequently as users.where(...).any?, and in the former case, any? behavior is not equivalent to exists?, and is not behaving similarly to empty?.


[source,ruby]
----
# bad
users.where(active: true).present?
users.where(active: true).blank?

# good
users.where(active: true).any?
users.where(active: true).empty?

# good - the collection is used after loading
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am referring to the "used" wording above.

Even though the collection will be used a few lines below, maybe only a fraction of it will be actually used with a batching iterator like `users.find_each { ...?

Or it will be further queried upon e.g. users.active? Or users.last(3).

Or, it will be used in a sub-query, and it doesn't meet the purpose to load them all e.g. Articles.recent.joins(:author).merge(users).

users.present?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced that preloading the list of records implicitly with present? is a practice we should recommend to everyone.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if there are hundreds of thousands of those records?

users.each(&:notify)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

----

=== Where with Ranges [[where-ranges]]

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