Rails: Reverse pagination from scratch


Reverse pagination is a trick to make paginated content more bookmarkable and SEO-friendly. Pages are numerated from big numbers (fresh content) to small numbers (oldest content), and each page keeps its content through time.

Let’s imagine we have a user has_many likes structure. I need this to show pagination in real life with eager loading and etc.

class User < ActiveRecord::Base
PER_PAGE = 10
  has_many :likes
end
...
class Like < ActiveRecord::Base
belongs_to :user
end

I’ll just put full gist and explain some important notes down below.

We probably should move reverse_paginate method to application_controller in order to stay DRY, but i’ll leave it to you . We also need to implement helper to show pagination in views.

module PaginationHelper
def reverse_links_pagination
pagination_element = content_tag :div, '', :class => 'pagination'
    (1..@paginator.total_pages).to_a.reverse.each do |page|
pagination_element << link_to(page, users_path(:page => page), :class => "#{ page == @paginator.page ? 'active' : '' }"
end

pagination_element
end
end

And now you can use reverse pagination in views

= render @users
= reverse_links_pagination

That’s all. If you have better solution, please let me know!