Skip to content

Commit d21f959

Browse files
committed
Fix loaded relation batching with limits and reverse order
1 parent 4867559 commit d21f959

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

activerecord/lib/active_record/relation/batches.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,13 @@ def batch_on_loaded_relation(relation:, start:, finish:, order:, batch_limit:)
341341

342342
if start || finish
343343
records = records.filter do |record|
344-
(start.nil? || record.id >= start) && (finish.nil? || record.id <= finish)
344+
id = record.id
345+
346+
if order == :asc
347+
(start.nil? || id >= start) && (finish.nil? || id <= finish)
348+
else
349+
(start.nil? || id <= start) && (finish.nil? || id >= finish)
350+
end
345351
end
346352
end
347353

activerecord/test/cases/batches_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,23 @@ def test_in_batches_when_loaded_runs_no_queries_with_start_and_end_arguments
506506
assert_equal posts.size - 2, batch_count
507507
end
508508

509+
def test_in_batches_when_loaded_runs_no_queries_with_start_and_end_arguments_and_reverse_order
510+
posts = Post.all.order(id: :asc)
511+
posts.load
512+
batch_count = 0
513+
514+
start_id = posts.map(&:id)[-2]
515+
finish_id = posts.map(&:id)[1]
516+
assert_queries_count(0) do
517+
posts.in_batches(of: 1, start: start_id, finish: finish_id, order: :desc) do |relation|
518+
batch_count += 1
519+
assert_kind_of ActiveRecord::Relation, relation
520+
end
521+
end
522+
523+
assert_equal posts.size - 2, batch_count
524+
end
525+
509526
def test_in_batches_when_loaded_can_return_an_enum
510527
posts = Post.all
511528
posts.load

0 commit comments

Comments
 (0)