According to the Rails Guide on Active Record Query Interface, the correct way to iterate through all records is by using find_each.
Using Foo.all.each will load the entire table into memory, instantiating all the rows; then iterate through the instances. find_each does this in batches, which is more efficient in terms of memory usage.
From the guide:
The
find_eachmethod retrieves a batch of records and then yields each record to the block individually as a model. In the following example,find_eachwill retrieve 1000 records (the current default for bothfind_eachandfind_in_batches) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:
User.find_each do |user|
  NewsLetter.weekly_deliver(user)
end
References:
yes, Foo.all.
all is deprecated on an ActiveRecord::Relation (eg. Foo.where(true)), not on ActiveRecord::Base.
http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-all
Release notes for Rails 4:
Model.all now returns an ActiveRecord::Relation, rather than an array of records. Use Relation#to_a if you really want an array.
So your code will look like this:
Foo.all.to_a.each do |foo|
  # whatever
end
See http://guides.rubyonrails.org/4_0_release_notes.html#active-record
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With