Skip to content

Instantly share code, notes, and snippets.

@ezekg
Last active August 17, 2022 14:41
Show Gist options
  • Save ezekg/5ff5e965410885501198235d6a779ceb to your computer and use it in GitHub Desktop.
Save ezekg/5ff5e965410885501198235d6a779ceb to your computer and use it in GitHub Desktop.
Proof of concept cursor pagination in Rails, with support for UUID primary keys.
page_dir = :desc
page_model = Post.reorder(created_at: page_dir)
page_cursor = page_model.first.id
page_size = 3
page_num = 0
loop do
page_num += 1
page = page_model.where.not(id: page_cursor)
.where(
page_dir == :desc ? 'created_at <= (?)' : 'created_at >= (?)',
page_model.where(id: page_cursor).select(:created_at).limit(1),
)
.limit(page_size)
puts "Found #{page.length} records: dir=#{page_dir} page=#{page_num} cursor=#{page_cursor}"
puts " IDs: #{page.map(&:id)}"
break if
page.length != page_size
page_cursor = page.last.id
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment