Ruby-on-rails Kaminari & Rails 分页 - 未定义的方法 `current_page'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11200330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Kaminari & Rails pagination - undefined method `current_page'
提问by time
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:
这功能很好,因为主题视图减少到两个帖子。但是,当我将其添加到 show.html.erb 时:
<%= paginate @topic.posts %>
I'm given this error:
我得到了这个错误:
undefined method `current_page' for #<ActiveRecord::Relation:0x69041c9b2d58>
回答by Nicolas Garnil
Try with:
尝试:
def show
@topic = Topic.find(params[:id])
@posts = @topic.posts.page(params[:page]).per(2)
end
And then:
进而:
<%= paginate @posts %>
回答by Darren Hicks
If you get pagination errors in Kaminari like
如果您在 Kaminari 中遇到分页错误,例如
undefined method `total_pages'
未定义的方法“total_pages”
or
或者
undefined method `current_page'
未定义的方法“current_page”
it is likely because the AR scope you've passed into paginatehas not had the pagemethod called on it.
这可能是因为您传入的 AR 范围paginate没有page调用该方法。
Make sure you always call pageon the scopes you will be passing in to paginate!
确保你总是调用page你将传入的范围paginate!
This also holds true if you have an Array that you have decorated using Kaminari.paginate_array
如果您有一个使用装饰的数组,这也适用 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...
或者使用您自己的非 AR 阵列...
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) %>
回答by Kleber S.
Some time ago, I had a little problem with kaminari that I solved by using different variable names for each action.
前段时间,我遇到了一个关于 kaminari 的小问题,我通过为每个动作使用不同的变量名来解决这个问题。
Let's say in the indexaction you call something like:
假设index您在操作中调用以下内容:
def index
@topic = Topic.all.page(params[:page])
end
The indexview 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.
该index视图可以正常工作,<%= paginate @topic %>但是如果您想在任何其他操作中使用相同的变量名称,则会出现类似错误。
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.
请给一个镜头。

