Faking a Will Paginate Collection on an Active Resource model

This post was written by Scott Davis. Read other posts by Scott Davis.

To follow up on my other blog post about Paginating an ActiveResource model and to_xml I figured I should include the client-side code so you can see how to actually use will paginate helpers out of the box to paginate an ActiveResource request.

This is example code from my model:

  def self.paginate(*args, &block)
    options = args.pop
    page, per_page, total_entries = wp_parse_options(options)
 
    WillPaginate::Collection.create(page, per_page, total_entries) do |pager|
      count_options = options.except :page, :per_page, :total_entries, :finder
      find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page) 
 
      args << find_options
      # @options_from_last_find = nil
      find_results = self.find(*args, &block)
      pager.replace find_results
      # magic counting for user convenience:
      pager.total_entries = find_results.total_entries unless find_results.blank?
    end
  end

Example View code:

<%= render :partial => 'list' %>
<%= will_paginate(@model)%>

About the author: Scott is a 23-year-old Web Developer working at SmartLogic Solutions in Baltimore, Maryland. Languages: Ruby, C, PHP, ColdFusion, ActionScript, Flex

Tags:

Leave a Reply