Created
January 28, 2017 19:03
-
-
Save oboxodo/61e391f58a5a2b946eb3283c4b32c824 to your computer and use it in GitHub Desktop.
MVP for adding cursor based pagination to an scaffolded Rails blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
commit 3babf31134cafb211041202d19fa6f5a9359aed1 | |
Author: Diego Algorta <diego@oboxodo.com> | |
Date: Sat Jan 28 15:59:06 2017 -0300 | |
Add cursor based pagination | |
diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb | |
index 16bba99..a921aff 100644 | |
--- a/app/controllers/posts_controller.rb | |
+++ b/app/controllers/posts_controller.rb | |
@@ -4,7 +4,9 @@ class PostsController < ApplicationController | |
# GET /posts | |
# GET /posts.json | |
def index | |
- @posts = Post.all | |
+ @posts = Post.paginated | |
+ @posts = @posts.before(params[:before]) if params[:before] | |
+ @posts = @posts.after(params[:after]) if params[:after] | |
end | |
# GET /posts/1 | |
diff --git a/app/models/post.rb b/app/models/post.rb | |
index 791dcb5..817ac44 100644 | |
--- a/app/models/post.rb | |
+++ b/app/models/post.rb | |
@@ -1,2 +1,5 @@ | |
class Post < ActiveRecord::Base | |
+ scope :paginated, -> { order(:id).limit(5) } | |
+ scope :before, -> (id) { paginated.reverse_order.where("posts.id < ?", id).reverse } | |
+ scope :after, -> (id) { paginated.where("posts.id > ?", id) } | |
end | |
diff --git a/app/views/posts/index.html.erb b/app/views/posts/index.html.erb | |
index 9985e4f..c757e6f 100644 | |
--- a/app/views/posts/index.html.erb | |
+++ b/app/views/posts/index.html.erb | |
@@ -27,3 +27,5 @@ | |
<br> | |
<%= link_to 'New Post', new_post_path %> | |
+<%= link_to 'Prev', posts_path(before: @posts.first) %> | |
+<%= link_to 'Next', posts_path(after: @posts.last) %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment