Will_Paginate - 如何获取所有分页对象 ID 的数组?
我正在使用 will_paginate
2.3.x gem,并且尝试获取 WillPaginate::Collection 中对象的所有 id 的数组。有没有一种简单的方法来迭代集合中的所有项目?对于 ActiveRecord 集合,这很简单:
all_ids = MyObject.find(:all).map { |o| o.id }
但是,当分页时,集合仅返回第一页中的 N 个元素:
not_all_ids = MyObject.paginate(:page => 1).map { |o| o.id }
我想要的是遍历集合中的所有页面。基本上,我正在寻找一种检索下一页的方法。有什么想法吗?谢谢。
编辑 - 我正在使用rails 2.3。另外,我在某些条件下使用分页,但为了简化而放弃了它们:
MyObject.paginate(:conditions => [...], :include => [...], :page => 1)
I'm using will_paginate
2.3.x gem and I'm trying to get an array of all the ids of the objects that are in the WillPaginate::Collection. Is there a simple way to iterate all the items in the collection? With ActiveRecord collection this is simple:
all_ids = MyObject.find(:all).map { |o| o.id }
However, when paginated, the collection returns only the N elements that are in the first page:
not_all_ids = MyObject.paginate(:page => 1).map { |o| o.id }
What I want is to go through all the pages in the collection. Basically, I'm looking for a method that retrieves the next page. Any thoughts? thanks.
EDIT - I'm using rails 2.3. Also, I'm using pagination with some conditions but dropped them to simplify:
MyObject.paginate(:conditions => [...], :include => [...], :page => 1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以这样做:
但是为什么在这种情况下使用分页呢?
会更快,并且使用更少的资源...如果您的数据库包含 10000 个元素并且您一次迭代 10 个元素,那么您将对数据库进行 1000 cals 与 1 :-)
ps: 我正在使用 < em>.select("id") 所以生成的请求是:
VS
我还使用了一个很好的快捷方式 map(&:id),这相当于.map { |o| o.id }
You could do something like that :
But why using paginate in this case ?
will be faster, and will use less resources ... if you're db contains 10000 elements and you're iterating 10 at a times you'll make 1000 cals to your db vs 1 :-)
ps: I'm using .select("id") so the request generated is :
VS
I'm also using a nice shortcut map(&:id), this is the equivalent of .map { |o| o.id }