instance method each_record

Ruby on Rails 8.0.4

Since v5.2.8.1

Available in: v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

each_record(&block)

Looping through a collection of records from the database (using the all method, for example) is very inefficient since it will try to instantiate all the objects at once.

In that case, batch processing methods allow you to work with the records in batches, thereby greatly reducing memory consumption.

Person.in_batches.each_record do |person|
  person.do_awesome_stuff
end

Person.where("age > 21").in_batches(of: 10).each_record do |person|
  person.party_all_night!
end

If you do not provide a block to #each_record, it will return an Enumerator for chaining with other methods:

Person.in_batches.each_record.with_index do |person, index|
  person.award_trophy(index + 1)
end

Parameters

block block
Source
# File activerecord/lib/active_record/relation/batches/batch_enumerator.rb, line 53
      def each_record(&block)
        return to_enum(:each_record) unless block_given?

        @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: true, cursor: @cursor, order: @order).each do |relation|
          relation.records.each(&block)
        end
      end

Defined in activerecord/lib/active_record/relation/batches/batch_enumerator.rb line 53 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Batches::BatchEnumerator

Type at least 2 characters to search.

↑↓ navigate · open · esc close