Skip to content

Instantly share code, notes, and snippets.

@crespire
Last active August 13, 2024 19:41
Show Gist options
  • Save crespire/049d6b0f064756fc31345b9e85e9a43f to your computer and use it in GitHub Desktop.
Save crespire/049d6b0f064756fc31345b9e85e9a43f to your computer and use it in GitHub Desktop.
Pluck in batches
# Assuming Rails AR is available
# This should let us pluck stuff from a big collection in batches
# We add the load: true option if we want to load the relaion beforehand.
# Because we are plucking anyway, we don't need to preload
# See: https://github.com/rails/rails/issues/47462
Model.where(some_id: 15).in_batches do |relation|
relation.pluck(:attr1, :attr2).each do |row|
# stuff
end
end
# To set a custom batch size
Model.where(some_id: 15).in_batches(of: 50 do |relation|
relation.pluck(:attr1, :attr2).each do |row|
# stuff
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment