This browser does not support basic Web standards, preventing the display of our site's intended design. May we suggest that you upgrade your browser?

Web Development Code Library RailsPaginate an existing resultset

Paginate an existing resultset

Sometimes you have a resultset that you can’t use with the built-in Rails pagination tool. This code below will fix the issue for you.

  # Place this in application.rb

  # Paginate an existing resultset.
  # Example:
  #   @pages, @users = paginate_collection User.find_custom_query, :page => @params[:page]
  
  def paginate_collection(collection, options = {})
    default_options = {:per_page => 10, :page => 1}
    options = default_options.merge options
    
    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end
Excellence. Our Measure. Our Motto. Our Goal.