Last active
October 18, 2019 12:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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