基于 Cursor 的 ActiveRecord 分页
This library allows to paginate through an ActiveRecord relation using cursor pagination.
It also supports ordering by any column on the relation in either ascending or descending order.
Cursor pagination allows to paginate results and gracefully deal with deletions / additions on previous pages. Where a regular limit / offset pagination would jump in results if a record on a previous page gets deleted or added while requesting the next page, cursor pagination just returns the records following the one identified in the request.
To learn more about cursor pagination, check out the "How does it work?" section below.
If you need support for older ruby and rails, please open an issue.
Add this line to your application's Gemfile:
gem "activerecord_cursor_paginate"And then run:
$ bundle installLet's assume we have a Post model of which we want to fetch some data and then paginate through it.
Therefore, we first apply our scopes, where clauses or other functionality as usual:
posts = Post.where(author: "Jane")And then we create our paginator to fetch the first response page:
paginator = posts.cursor_paginate
# Total number of records to iterate by this paginator
paginator.total_count # => 145
page = paginator.fetch
page.records # => [#, #, ..., #]
# Number of records in this page
page.count # => 10
page.empty? # => false
page.cursors # => ["MQ", "Mg", ..., "MTA"]
| |
| |
page.previous_cursor # => "MQ" |
page.next_cursor # => "MTA" -------------|
page.has_previous? # => false
page.has_next? # => trueNote that any ordering of the relation at this stage will be ignored by the gem. Take a look at the next section "Ordering" to see how you can have an order different than ascending IDs.
To then get the next result page, you simply need to pass the last cursor of the returned page item via:
paginator = posts.cursor_paginate(after: "MTA")This will then fetch the next result page.
You can also just as easily paginate to previous pages by using before instead of after and using the first cursor of the current page.
paginator = posts.cursor_paginate(before: "MQ")By default, this will always return up to 10 results. But you can also specify how many records should be returned via limit parameter.
paginator = posts.cursor_paginate(after: "MTA", limit: 2)paginator = posts.cursor_paginate(before: "MQ", limit: 2)You can also easily iterate over the whole relation:
paginator = posts.cursor_paginate
# Will lazily iterate over the pages.
paginator.pages.each do |page|
# do something with the page
endAs said, this gem ignores any previous ordering added to the passed relation. But you can still paginate through relations with an order different than by ascending IDs.
You can specify a different column and direction to order the results by via an order parameter.
# Order records ascending by the `:author` field.
paginator = posts.cursor_paginate(order: :author)
# Order records descending by the `:author` field.
paginator = posts.cursor_paginate(order: { author: :desc })
# Order records ascending by the `:author` and `:title` fields.
paginator = posts.cursor_paginate(order: [:author, :title])
# Order records ascending by the `:author` and descending by the `:title` fields.
paginator = posts.cursor_paginate(order: { author: :asc, title: :desc })The gem implicitly appends a primary key column to the list of sorting columns. It may be useful to disable it for the table with a UUID primary key or when the sorting is done by a combination of columns that are already unique.
paginator = UserSettings.cursor_paginate(order: :user_id, append_primary_key: false)Important:
If your app regularly orders by another column, you might want to add a database index for this.
Say that your order column is author then you'll want to add a compound index on (author, id).
If your table is called posts you can use a query like this in MySQL or PostgreSQL:
CREATE INDEX index_posts_on_author_and_id ON posts (author, id)Or you can just do it via an ActiveRecord::Migration:
class AddAuthorAndIdIndexToPosts 2
ORDER BY id ASC
LIMIT 2Which would return posts #3 and #4. If we now want to paginate back, we can
request the posts that came before the first post, whose cursor would be
"Mw" (can get via page.previous_cursor):
paginator = relation.cursor_paginate(limit: 2, before: "Mw")
page = paginator.fetchSince we now paginate backward, the resulting SQL query needs to be flipped around to get the last two records that have an ID smaller than the given one:
SELECT *
FROM posts
WHERE id 'Jane' OR (author = 'Jane') AND (id > 4))
ORDER BY author ASC, id ASC
LIMIT 2You can see how the cursor is being used by the WHERE clause to uniquely
identify the row and properly filter based on this. We only want to get
records that either have a name that is alphabetically after "Jane" or
another "Jane" record with an ID that is higher than 4. We will get the
records #5 and #2 as response.
When using a custom order, this affects both filtering as well as
ordering. Therefore, it is recommended to add an index for columns that are
frequently used for ordering. In our test case we would want to add a compound
index for the (author, id) column combination. Databases like MySQL and
PostgreSQL are able to then use the leftmost part of the index, in our case
author, by its own or can use it combined with the id index.
Thanks to rails_cursor_pagination gem for the original ideas.
After checking out the repo, run bundle install to install dependencies. Then, run bundle exec rake to run the linter and tests. This project uses multiple Gemfiles to test against multiple versions of Active Record; you can run the tests against the specific version with BUNDLE_GEMFILE=gemfiles/activerecord_71.gemfile bundle exec rake test.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/healthie/activerecord_cursor_paginate.
The gem is available as open source under the terms of the MIT License.
暂无开放 Issues,或尚未同步最近议题。