Rails - Paginate a collection or an array
Yesterday, I was looking for a way to paginate my collection. While searching online I found this wonderful snippet by Canadaduane that does the job very neatly.
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
The above snippet can be invoked using
@pages, @users = paginate_collection User.find_custom_query, :page => @params[:page]
Access the original post: Paginate an already-fetched result set (i.e. collection or array)
Also check out snippet by toolmantim on the above URL for block.
0 Comments:
Post a Comment
<< Home