# How to get cursor / lazy semantics from find(:all)

**URL:** <https://www.ruby-forum.com/t/how-to-get-cursor-lazy-semantics-from-find-all/161147>\
**Category:** Rails\
**Created:** [February 23, 2009, 9:37pm UTC](https://www.ruby-forum.com/t/how-to-get-cursor-lazy-semantics-from-find-all/161147 "2009-02-23T21:37:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kschell](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/a698b9/32.png) [@kschell](https://www.ruby-forum.com/u/kschell)\
**Post date:** [February 23, 2009, 9:37pm UTC](https://www.ruby-forum.com/t/how-to-get-cursor-lazy-semantics-from-find-all/161147/1 "2009-02-23T21:37:41Z")

</div>

I’m trying to figure out it there’s some alternative to find(:all)  
that can avoid instantiating every object at once, when I know that  
I’m just going to iterate over the collection and throw it away. E.g.

def batch\_process  
User.find(:all).each do |user|  
batch\_process\_one\_user(user)  
end  
end

Unfortunately, this may instantiate millions of User objects and use  
up GB of memory, which is not acceptable. I’ve been digging through  
docs and code trying to figure out how I can do this within Rails,  
rather than having to go down to the raw DB connection and build from  
there, or pushing everything into a stored procedure.

Thanks,

-kevin

---

<div class="post-metadata">

**Author:** ![kschell](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/a698b9/32.png) [@kschell](https://www.ruby-forum.com/u/kschell)\
**Post date:** [February 23, 2009, 9:38pm UTC](https://www.ruby-forum.com/t/how-to-get-cursor-lazy-semantics-from-find-all/161147/2 "2009-02-23T21:38:16Z")

</div>

On Feb 23, 8:28 pm, Kevin S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> I’m trying to figure out it there’s some alternative to find(:all)  
> that can avoid instantiating every object at once, when I know that  
> I’m just going to iterate over the collection and throw it away. E.g.

> <https://github.com/rails/rails/commit/d13623ca46c82120c398f4634e206422fc3ad7ea>

?

Fred

---

<div class="post-metadata">

**Author:** ![kschell](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/a698b9/32.png) [@kschell](https://www.ruby-forum.com/u/kschell)\
**Post date:** [February 23, 2009, 11:20pm UTC](https://www.ruby-forum.com/t/how-to-get-cursor-lazy-semantics-from-find-all/161147/3 "2009-02-23T23:20:01Z")

</div>

Thanks! That’s close enough and easy to backport. In principle, a  
solution that did O(1) queries, rather than O(N) would be nice, but  
the reduction in memory use at least gets me back to something  
tolerable.

-kevin
