Tim Grüns
Tim Grüns

Reputation: 59

Paginate in Rails 3 issues

I'm currently working on a Reddit clone app that I had written in Rails 2 and I'm trying to bring it up to speed with new features in Rails 3. The app is very simple, it has a Links scaffold which has :url, :description, :points, and :created_at. The app routes to links#submissions where you can view all submitted links and submit a new link as well.

I've run into a problem with the paginate method in Rails 2 when displaying the links on the submissions page. I am currently running Rails 3.2.3 and I understand that I need to use the gem will_paginate in Rails 3 (which I have included in my Gemfile) but whenever I try to pull up localhost:3000 I get this error message:

NoMethodError in LinksController#submissions...
undefined method paginate for #<LinksController:0x00000102ff5f98>

specifically on line 90 of the Links controller.

Here is what I have in my LinksController.rb (lines 90-93).

@link_pages, @Links = paginate :links, :order => order, :per_page => 20
@header_text = case ordering
    when 'hot' then 'Top rated submissions'
when 'new' then 'Latest submissions'

Is this not the correct way to use paginate in Rails 3?

Upvotes: 1

Views: 963

Answers (2)

Nathan
Nathan

Reputation: 8026

For will_paginate, you should use something like this in your controller:

@links = Link.paginate(:page => params[:page], :per_page => 20)

In your view, the links for the given page will be stored in the @links instance variable. You can iterate over that collection and display the links.

To show the links to other pages (of links), you use this somewhere in the view:

will_paginate @links

You can find more help for will_paginate here: https://github.com/mislav/will_paginate

However, for Rails 3, I prefer kaminari instead of will_paginate. It uses Rails 3 scopes.

It looks like this in the controller:

@links = Link.page(params[:page]).per(20)

And this in the view:

paginate @links

You can read more about kaminari here: https://github.com/amatsuda/kaminari

Also you can watch Ryan's Railscast on kaminari here: http://railscasts.com/episodes/254-pagination-with-kaminari

Upvotes: 4

Sam Peacey
Sam Peacey

Reputation: 6034

You need to call paginate on the model, so

Link.paginate :page => params[:page], :per_page => 20

or

Link.[arel query].paginate :page => params[:page], :per_page => 20

should work.

To order by created descending example, you'd do something like:

Link.order("created_at DESC").paginate :page => params[:page], :per_page => 20

Upvotes: 1

Related Questions