Skip to content

Instantly share code, notes, and snippets.

@the-spectator
Last active October 18, 2019 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save the-spectator/28b1176f98cc2f66e870755bb2334545 to your computer and use it in GitHub Desktop.
Save the-spectator/28b1176f98cc2f66e870755bb2334545 to your computer and use it in GitHub Desktop.
Introduce find_in_batches_with_order for having find in batches with order
# Create file config/initializers/find_in_batches_with_order.rb with follwing code.
ActiveRecord::Batches.class_eval do
## Only flat order structure is supported now
## example: [:forename, :surname] is supported but [:forename, {surname: :asc}] is not supported
def find_in_batches_with_order(ids: nil, order: [], batch_size: 1000)
relation = self
arrangement = order.dup
index = order.find_index(:id)
unless index
arrangement.push(:id)
index = arrangement.length - 1
end
ids ||= relation.order(*arrangement).pluck(*arrangement).map{ |tupple| tupple[index] }
ids.each_slice(batch_size) do |chunk_ids|
chunk_relation = relation.where(id: chunk_ids).order(*order)
yield(chunk_relation)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment