John Bachir John Bachir - 1 month ago 7
Ruby Question

Equivalent of find_each for foo_ids?

Given this model:

class User < ActiveRecord::Base
has_many :things
end


Then we can do this::

@user = User.find(123)
@user.things.find_each{ |t| print t.name }
@user.thing_ids.each{ |id| print id }


There are a large number of
@user.things
and I want to iterate through only their ids in batches, like with
find_each
. Is there a handy way to do this?

The goal is to:


  • not load the entire
    thing_ids
    array into memory at once

  • still only load arrays of
    thing_ids
    , and not instantiate a
    Thing
    for each id


Answer

It is, unfortunately, not a one-liner or helper that will allow you to do this, so instead:

limit = 1000
offset = 0
loop do
  batch = @user.things.limit(limit).offset(offset).pluck(:id)
  batch.each { |id| puts id }
  break if batch.count < limit
  offset += limit
end