Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:rails-best-practices/find-each
Language: Ruby
Severity: Notice
Category: Best Practices
Description
This rule ensures efficient use of memory when dealing with large collections of ActiveRecord (AR) objects. The each method loads all the objects at once into memory, which can cause significant performance issues if the collection is large. In contrast, find_each loads a batch of records (1000 by default) into memory, processes them, and then loads the next batch, significantly reducing memory usage.
This rule is especially relevant when dealing with large datasets, where the each method can lead to ‘out of memory’ errors.
To adhere to this rule, replace each with find_each when iterating over collections of ActiveRecord objects. For example, instead of writing Foo.all.each, write Foo.all.find_each. Similarly, replace Foo.where('foo > 42').each with Foo.where('foo > 42').find_each.