John Bachir John Bachir - 10 months ago 54
Ruby Question

Equivalent of find_each for foo_ids?

Given this model:

class User < ActiveRecord::Base
has_many :things

Then we can do this::

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

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

The goal is to:

  • not load the entire
    array into memory at once

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

Answer Source

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