简体   繁体   中英

Will_Paginate - how to get an array of all paginated object ids?

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)

You could do something like that :

ids = MyObject.select("id").paginate(:page => 1)
if ids.total_pages > 1
  (2..ids.total_pages).each do |page|
    ids << MyObject.select("id").paginate(:page => page)
  end
end
ids = ids.map(&:id)

But why using paginate in this case ?

ids = MyObject.select("id").map(&:id)

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 :

SELECT id from users;

VS

SELECT * FROM users;

I'm also using a nice shortcut map(&:id) , this is the equivalent of .map { |o| o.id }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM