Kaminari & Rails pagination - undefined method `current_page'
Asked Answered
L

3

31

I searched and searched, but nothing solved my problem. Here's my controller:

def show
    @topic = Topic.find(params[:id])
    @topic.posts = @topic.posts.page(params[:page]).per(2) # 2 for debugging
end

That functions just fine, because the topic view is reduced to two posts. However, when I add this to show.html.erb:

<%= paginate @topic.posts %>

I'm given this error:

undefined method `current_page' for #<ActiveRecord::Relation:0x69041c9b2d58>
Loring answered 26/6, 2012 at 3:14 Comment(0)
H
47

Try with:

def show
  @topic = Topic.find(params[:id])
  @posts = @topic.posts.page(params[:page]).per(2)
end

And then:

<%= paginate @posts %>
Honeywell answered 26/6, 2012 at 3:31 Comment(0)
L
22

If you get pagination errors in Kaminari like

undefined method `total_pages'

or

undefined method `current_page'

it is likely because the AR scope you've passed into paginate has not had the page method called on it.

Make sure you always call page on the scopes you will be passing in to paginate!

This also holds true if you have an Array that you have decorated using Kaminari.paginate_array

Bad:

<% scope = Article.all    # You forgot to call page :(  %>
<%= paginate(scope)       # Undefined methods...        %>

Good:

<% scope = Article.all.page(params[:page]) %>
<%= paginate(scope) %>

Or with a non-AR array of your own...

Bad:

<% data = Kaminari.paginate_array(my_array)   # You forgot to call page :(        %>
<%= paginate(data)                            # Undefined methods...     %>

Again, this is good:

<% data = Kaminari.paginate_array(my_array).page(params[:page]) %>
<%= paginate(data) %>
Labiche answered 30/4, 2015 at 6:10 Comment(0)
E
3

Some time ago, I had a little problem with kaminari that I solved by using different variable names for each action.

Let's say in the index action you call something like:

def index
  @topic = Topic.all.page(params[:page])
end

The index view works fine with <%= paginate @topic %> however if you want to use the same variable name in any other action, it throu an error like that.

def list
  # don't use @topic again. choose any other variable name here
  @topic_list = Topic.where(...).page(params[:page])
end

This worked for me.

Please, give a shot.

Eure answered 26/6, 2012 at 3:40 Comment(1)
(I know it's old) Any idea on why this could ever happen?Headgear

© 2022 - 2024 — McMap. All rights reserved.