Kaminari & Rails pagination - undefined method `current_page'

試著忘記壹切 提交于 2019-12-09 14:00:49

问题


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>

回答1:


Try with:

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

And then:

<%= paginate @posts %>



回答2:


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) %>



回答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.



来源:https://stackoverflow.com/questions/11200330/kaminari-rails-pagination-undefined-method-current-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!