<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: pagination code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 03:36:32 GMT</pubDate>
    <description>DZone Snippets: pagination code</description>
    <item>
      <title>Paginate an already-fetched result set (i.e. collection or array)</title>
      <link>http://snippets.dzone.com/posts/show/389</link>
      <description>Sometimes it's nearly impossible to paginate a result set using the built-in :limit and :offset parameters of find(:all). Instead, you can fetch a complicated query and paginate the results afterward.&lt;br /&gt;&lt;br /&gt;Add the following to application.rb:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  def paginate_collection(collection, options = {})&lt;br /&gt;    default_options = {:per_page =&gt; 10, :page =&gt; 1}&lt;br /&gt;    options = default_options.merge options&lt;br /&gt;    &lt;br /&gt;    pages = Paginator.new self, collection.size, options[:per_page], options[:page]&lt;br /&gt;    first = pages.current.offset&lt;br /&gt;    last = [first + options[:per_page], collection.size].min&lt;br /&gt;    slice = collection[first...last]&lt;br /&gt;    return [pages, slice]&lt;br /&gt;  end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Call it from within your action like this:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;@pages, @users = paginate_collection User.find_custom_query, :page =&gt; @params[:page]&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 16 Jun 2005 13:13:41 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/389</guid>
      <author>canadaduane (Duane Johnson)</author>
    </item>
  </channel>
</rss>
