Created
March 22, 2017 18:00
-
-
Save bf4/3810befdcbb09c577b692f90064a1bcf to your computer and use it in GitHub Desktop.
ActiveRecord Rails Find Relations in Batches
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
# Finds and yields relations in batches. Adapted from record.find_in_batches since that yields | |
# arrays and we want to operate on relationships. | |
# Adapted from: | |
# https://github.com/rails/rails/blob/4-2-stable/activerecord/lib/active_record/relation/batches.rb#L98-L115 | |
def find_in_batches(target, batch_size: default_batch_size, start: nil) | |
relation = target | |
if logger && (target.arel.orders.present? || target.arel.taken.present?) | |
logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size") | |
end | |
relation = relation.reorder(target.send(:batch_order)).limit(batch_size) | |
records = start ? relation.where(target.table[target.primary_key].gteq(start)) : relation | |
while (records_size = records.length) > 0 | |
primary_key_offset = records.last.id | |
fail "Primary key not included in the custom select clause" unless primary_key_offset | |
yield records | |
break if records_size < batch_size | |
records = relation.where(target.table[target.primary_key].gt(primary_key_offset)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment