Rails 3,will_paginate 超过现有的有限活动记录结果
我在分页方面遇到了很大的问题。
我的模型中有一个定义为范围的查询:
scope :published_and_valid, joins(...).where(...)
在我的控制器中,我有时只想获得前 20 个结果。
.limit(20)
现在我希望能够对这 20 个结果进行分页(每页 5 个)
,我尝试这样做:
@articles = Article.published_and_valid.limit(20).paginate(:page => params[:page])
这确实不起作用,因为在我看来,结果是所有文章的分页结果
I'm having a big problem with will paginate.
I have a query defined as scope in my model:
scope :published_and_valid, joins(...).where(...)
In my controller I sometimes just want to have the top 20.
.limit(20)
Now I want to be able to paginate over these 20 results (5 per page)
And I try to do this:
@articles = Article.published_and_valid.limit(20).paginate(:page => params[:page])
This does not work as the result in my view is a pagineted result for ALL articles
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来 will_paginate 在您的关系上强加了自己的
limit
子句来进行分页。经过一些实验,我发现执行此操作的最简单方法是立即加载结果集并使用 数组扩展 来执行实际的分页。这是一个简单的例子;请注意,您必须 require
will_paginate/array
;您可能希望在初始化程序或其他地方执行此操作。请注意,它对Array
进行了猴子补丁以使其具有paginate
方法。[更新]
另一种选择是根据结果集大小将
total_entires
选项传递给 will_paginate。你不能传入20个,因为你不能保证返回完整的20个结果;通过传入
count
属性,您可以确保分页正确。It looks like will_paginate imposes its own
limit
clause on your relation in order to do the paging. After some experimentation, the easiest way I could find to do this is to do eager-loading of the result set and use the functionality contained in the array extensions to do the actual pagination.Here's a quick example; note that you have to require
will_paginate/array
; you may wish to do this in an initializer or somewhere else. Note that it does monkey-patchArray
to have thepaginate
method.[Update]
Another option is to pass in the
total_entires
option to will_paginate based on the result set size.You can't pass in 20 as you can't guarantee that a full 20 results will be returned; by passing in the
count
attribute, you can ensure that the pagination will be correct.