]> git.openstreetmap.org Git - rails.git/blob - app/controllers/concerns/pagination_methods.rb
Fix right sidebar background
[rails.git] / app / controllers / concerns / pagination_methods.rb
1 module PaginationMethods
2   extend ActiveSupport::Concern
3
4   private
5
6   ##
7   # limit selected items to one page, get ids of first item before/after the page
8   def get_page_items(items, includes: [], limit: 20)
9     id_column = "#{items.table_name}.id"
10     page_items = if params[:before]
11                    items.where("#{id_column} < ?", params[:before]).order(:id => :desc)
12                  elsif params[:after]
13                    items.where("#{id_column} > ?", params[:after]).order(:id => :asc)
14                  else
15                    items.order(:id => :desc)
16                  end
17
18     page_items = page_items.limit(limit)
19     page_items = page_items.includes(includes)
20     page_items = page_items.sort.reverse
21
22     newer_items_id = page_items.first.id if page_items.count.positive? && items.exists?(["#{id_column} > ?", page_items.first.id])
23     older_items_id = page_items.last.id if page_items.count.positive? && items.exists?(["#{id_column} < ?", page_items.last.id])
24
25     [page_items, newer_items_id, older_items_id]
26   end
27 end