class Car << ActiveRecord::Base
end
Car.all.each do |car|
# do stuff
end
This loads all the objects of type Car into memory (I think) and iterates through them. What I want instead is to iterate through all the ids and load them one at a time like this:
Car.all_ids.each do |id|
c = Car.find id
# do stuff
end
But all_ids doesn’t exist, is there an equivalent?
For Rails 2.3 and up (including Rails 3) the easiest solution is find_each:
This executes the query in batches for you automatically. The default batch size is 1000 but you can set your own. It also works alongside named scopes and ActiveRecord::Relations:
See http://guides.rubyonrails.org/active_record_querying.html#retrieving-multiple-objects-in-batches