Old Guy New Trick

An old guys journey to learn how to code.

Fixing stuck pages (pagination)


Author: John on December 03, 2015

I’ve used the will_paginate gem on several projects.  While migrating my posts from the old website to this new one, running my FlexBlogr engine, I discovered a problem.  The pagination was not working.  The setup for will_paginate is fairly straight forward, so let’s take a look at what is going on:

def index
  @posts = Post.paginate(page: params[:post], per_page: 5)
  respond_with @posts
end

Looks good to me.  I confirmed the general syntax by looking at an example on the github page for will_paginate.  So, what the heck is going on.  Time to get out the crow-bar, errr, pry-bar and take a look.

def index
  binding.pry
  @posts = Post.paginate(page: params[:post], per_page: 5)
  respond_with @posts
end

With that in place, I refreshed the page and took at look at my rails server console:

Started GET "/posts?page=2" for ::1 at 2015-12-03 14:27:18 -0500
Processing by PostsController#index as HTML
  Parameters: {"page"=>"2"}
  Post Load (0.6ms)  SELECT  "posts".* FROM "posts" WHERE (status != 'draft')  ORDER BY created_at DESC, "posts"."created_at" DESC LIMIT 10
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."remember_token" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["remember_token", "80a229211763b424add77593a76f9cbd59087a81"]]

From: /Users/jfhogarty/Documents/RoR/ognt_fbrr/app/controllers/posts_controller.rb @ line 8 PostsController#index:

     7: def index
 =>  8:   binding.pry
     9:   @posts = Post.paginate(page: params[:post], per_page: 5)
    10:   respond_with @posts
    11: end

[1] pry(#)> params
=> {"page"=>"2", "controller"=>"posts", "action"=>"index"}
[2] pry(#)>

Do you see the problem?  I’d admit, in my early days this one would take me a bit of time to noodle out.  But with some experience now engrained in my brain, I saw the issue immediately.

@posts = Post.paginate(page: params[:post], per_page: 5)

=> {"page"=>"2", "controller"=>"posts", "action"=>"index"}

See it?  In the controller  I have a typo.  In the params part of the code I had typed :post but I should have typed :page.  Here is the corrected code:

def index
  @posts = Post.paginate(page: params[:page], per_page: 5)
  respond_with @posts
end


Glad this one was a fairly easy fix. Now I need to track down some other bugs I discovered.

Learn Something New Every Day

Last Edited by: John on December 04, 2015