Pagination over custom-sorted collections?

I have a little web app where we need to paginate collections of
items. I’m trying to sort the collection and then pass it, sorted, to
a Paginator, and still be able to paginate through the collection,
across several pages, with the new sort order. The only thing I’m
doing differently from the regular scaffolding approach is this:

@order_pages =, @orders.length, 10, (params[:page]
||= 1).to_i)

It doesn’t work.

@orders is sorted when I hand it to Paginator. Am I skipping a step?
Does Paginator only work on run-of-the-mill SQL calls? I can’t seem to
figure this out.

I used Paginator in two steps with count_by_sql and find_by_sql.
Here’s an excerpt of what works for me.

 @page = (params[:page] ||= 1).to_i
 @items_per_page = (params[:items_per_page] ||= 20).to_i

 count_sql_query = "SELECT COUNT(*) FROM activities [...fancy

@activities_count = Activity.count_by_sql(count_sql_query)
@activity_pages =, @activities_count,
@items_per_page, @page)

 select_sql_query = "SELECT activities [...fancy query] LIMIT
  #{@activity_pages.current.offset}, #

@activities = Activity.find_by_sql(select_sql_query)

        - dan

Dan K. mailto:[email protected] tel:+1-415-233-1000

On Saturday, July 15, 2006, at 6:45 PM, Giles B. wrote:
Are you sure you need a custom paginator? The standard one is pretty
flexible. You can pass it options that you would normally use in a
find to get the output just the way you like it.


yes, I’m sure I need a custom paginator. I need to paginate over a
collection sorted outside of SQL. since a find uses SQL, and this
sorting occurs after the find, and after the SQL, I am absolutely
certain I need a custom paginator.

or actually I am not absolutely certain, but I’m pretty sure. the
code draws from three tables and needs to sort its result set by any
one of the data returned, i.e.,


…the last being not a property but a method which adds up the
fulfillment dates of custom options (duh) and then tacks on fourteen
days just to be safe. I am almost certain that passing that method
into find() as an argument would be more challenging than just
creating a custom paginator or, if necessary, writing my own. (but I
could be wrong!)

anyway!! I may have found what looks like a possible solution in a blog:

it is, of course, clean, pretty, and simple. :slight_smile:

hooray. :slight_smile:

Giles B.

On 16 Jul 2006 03:10:44 -0000, Kevin O.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs