I had a hard time with custom pagination at first. It was
intimidating and I didn’t find any of the online guides particularly
helpful. So here’s mine.
Kevin’s custom-pagination-in-four-easy-steps:
def list
# step 1: read and set the variables you'll need
page = (params[:page] ||= 1).to_i
items_per_page = 20
offset = (page - 1) * items_per_page
# step 2: do your custom find without doing any kind of limits or
offsets
# i.e. get everything on every page, don’t worry about pagination yet
@items = Item.find_with_some_custom_method(@some_variable)
# step 3: create a Paginator, the second variable has to be the
number of ALL items on all pages
@item_pages = Paginator.new(self, @items.length, items_per_page, page)
# step 4: only send a subset of @items to the view
# this is where the magic happens... and you don't have to do
another find
@items = @items[ offset…(offset + items_per_page - 1)]
end
HTH,
Kevin S.