Skip to content

Commit 385799a

Browse files
authored
Merge pull request rails#25274 from kamipo/fix_find_nth_with_limit_value
Fix `find_nth` with `limit_value`
2 parents b10f601 + 84f4ab9 commit 385799a

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

activerecord/lib/active_record/relation/finder_methods.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def first!
147147
def last(limit = nil)
148148
return find_last(limit) if loaded? || limit_value
149149

150-
result = limit(limit || 1)
150+
result = limit(limit)
151151
result.order!(arel_attribute(primary_key)) if order_values.empty? && primary_key
152152
result = result.reverse_order!
153153

@@ -536,8 +536,12 @@ def find_nth_with_limit(index, limit)
536536
self
537537
end
538538

539-
relation = relation.offset(offset_index + index) unless index.zero?
540-
relation.limit(limit).to_a
539+
if limit_value.nil? || index < limit_value
540+
relation = relation.offset(offset_index + index) unless index.zero?
541+
relation.limit(limit).to_a
542+
else
543+
[]
544+
end
541545
end
542546
end
543547

activerecord/test/cases/finder_test.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -497,7 +497,7 @@ def test_second_to_last
497497
assert_nil Topic.offset(5).second_to_last
498498

499499
#test with limit
500-
# assert_nil Topic.limit(1).second # TODO: currently failing
500+
assert_nil Topic.limit(1).second
501501
assert_nil Topic.limit(1).second_to_last
502502
end
503503

@@ -526,9 +526,9 @@ def test_third_to_last
526526
assert_nil Topic.offset(5).third_to_last
527527

528528
# test with limit
529-
# assert_nil Topic.limit(1).third # TODO: currently failing
529+
assert_nil Topic.limit(1).third
530530
assert_nil Topic.limit(1).third_to_last
531-
# assert_nil Topic.limit(2).third # TODO: currently failing
531+
assert_nil Topic.limit(2).third
532532
assert_nil Topic.limit(2).third_to_last
533533
end
534534

0 commit comments

Comments
 (0)