百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
A

activerecord_cursor_paginate

> 后端框架
开源

基于 Cursor 的 ActiveRecord 分页

157 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

基于 Cursor 的 ActiveRecord 分页

ActiveRecordCursorPaginate

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.

Requirements

  • Ruby 2.7+
  • Rails (ActiveRecord) 7.0+

If you need support for older ruby and rails, please open an issue.

Installation

Add this line to your application's Gemfile:

ruby
gem "activerecord_cursor_paginate"

And then run:

bash
$ bundle install

Usage

Let'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:

ruby
posts = Post.where(author: "Jane")

And then we create our paginator to fetch the first response page:

ruby
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? # => true

Note 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:

ruby
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.

ruby
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.

ruby
paginator = posts.cursor_paginate(after: "MTA", limit: 2)
ruby
paginator = posts.cursor_paginate(before: "MQ", limit: 2)

You can also easily iterate over the whole relation:

ruby
paginator = posts.cursor_paginate

# Will lazily iterate over the pages.
paginator.pages.each do |page|
  # do something with the page
end

Ordering

As 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.

ruby
# 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.

ruby
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:

sql
CREATE INDEX index_posts_on_author_and_id ON posts (author, id)

Or you can just do it via an ActiveRecord::Migration:

ruby
class AddAuthorAndIdIndexToPosts  2
ORDER BY id ASC
LIMIT 2

Which 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):

ruby
paginator = relation.cursor_paginate(limit: 2, before: "Mw")
page = paginator.fetch

Since 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:

sql
SELECT *
FROM posts
WHERE id  'Jane' OR (author = 'Jane') AND (id > 4))
ORDER BY author ASC, id ASC
LIMIT 2

You 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.

Credits

Thanks to rails_cursor_pagination gem for the original ideas.

Development

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.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/healthie/activerecord_cursor_paginate.

License

The gem is available as open source under the terms of the MIT License.

Issues· 1 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyactiverecordgempaginationrails

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架