Matt White
Matt White

Reputation: 117

Implementing paginate in Ruby without will_paginate gem

I am approximately one month into an online Ruby on Rails course and am currently tasked with implementing pagination without the help of the will_paginate gem. The site I am building displays a list of topics, which each contain a number of posts. The goal is to display 10 topics, or posts, per page.

Here is what I have so far:

I have created a Paginate module from which the Post and Topic models can call:

module Paginate
  def paginate(args = {})

    self.limit(10).offset(args[:page] * 10)

  end
end

This is what I am calling in my Topics Controller:

 def index
    params[:page] ||= 0  
    @topics = Topic.paginate(page: params[:page].to_i)
    authorize @topics
 end

I know this will only display the first 10 topics, I would have to manually enter a query string into the url to display each set of 10 (/topics?page=1 for instance).

Does anyone have any suggestions for a view helper method that could clean this up? I am unsure how I could write something to generate an html link to each set of 10.

Thank you,

Matt

Upvotes: 1

Views: 2419

Answers (1)

Max Williams
Max Williams

Reputation: 32933

The main thing that's missing from your code so far is that the paginate method needs to somehow return, along with the array of results, the total number of records, ie the number you would get back if you did that search without paginating. The reason you need this is so you know how to construct the helper, which will have (in the simplest case) one link per page.

eg if your page size is 10, and there are 46 records, that will be five pages in total. So your helper will have links to page 1, page 2, page 3, page 4, page 5, and also maybe "Previous" and "Next", or something along those lines.

WillPaginate communicates this by returning a new class of object, that extends Array (or extends ActiveRecord::Collection or whatever you normally get back from Topic.all), and adds in some extra methods like total_entries which tell you the extra info.

The advantage of this is that because paginate returns the same sort of thing that a normal search would, with a bit of extra info attached, you can subsititute a paginated search for a non-paginated search without having to change all the rest of your code: it's like a normal search with some extra "stuff".

The only bit of extra info you really need is the "total_entries" figure: you know which page you asked for and how many results per page, so you can calculate everything else you need for the pagination helper from these three numbers.

Note i'm not giving you the code here, just a pointer in the right direction.

Upvotes: 4

Related Questions