Skip to content

Remove total count comparison for next and previous page check #158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ These are the latest changes on the project's `master` branch that have not yet
Follow the same format as previous releases by categorizing your feature into "Added", "Changed", "Deprecated", "Removed", "Fixed", or "Security".
--->

## [0.5.0] - 2025-05-02

### Changed
- Removed a redundant check for the total amount of items in order to determine if there is a next or previous page. This gets rid of two `select count(*)` queries that were being executed, speeding up the pagination process.

## [0.4.0] - 2023-10-06

### Changed
Expand Down
17 changes: 8 additions & 9 deletions lib/rails_cursor_pagination/paginator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,10 @@ def custom_order_field?
# @return [TrueClass, FalseClass]
def previous_page?
if paginate_forward?
# When paginating forward, we can only have a previous page if we were
# provided with a cursor and there were records discarded after applying
# this filter. These records would have to be on previous pages.
@cursor.present? &&
filtered_and_sorted_relation.reorder('').size < total
# When paginating forward, if a cursor is present it must mean we have
# come from a previous page that has provided us a cursor. Therefore, we
# can assume that there is a previous page.
@cursor.present?
else
# When paginating backwards, if we managed to load one more record than
# requested, this record will be available on the previous page.
Expand All @@ -237,10 +236,10 @@ def next_page?
# requested, this record will be available on the next page.
records_plus_one.size > @page_size
else
# When paginating backward, if applying our cursor reduced the number
# records returned, we know that the missing records will be on
# subsequent pages.
filtered_and_sorted_relation.reorder('').size < total
# When paginating backward, if a cursor is present it must mean we have
# come from a next page that has provided us a cursor. Therefore, we
# can assume that there is a next page.
@cursor.present?
end
end

Expand Down