Forum: Ruby on Rails Re: custom find methods and pagination

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kevin S. (Guest)
on 2005-12-20 00:28
(Received via mailing list)
I had a hard time with custom pagination at first.  It was
intimidating and I didn't find any of the online guides particularly
helpful.  So here's mine.  :-)

Kevin's custom-pagination-in-four-easy-steps:

def list

	# step 1: read and set the variables you'll need
	page = (params[:page] ||= 1).to_i
	items_per_page = 20
	offset = (page - 1) * items_per_page

	# step 2: do your custom find without doing any kind of limits or
offsets
	#  i.e. get everything on every page, don't worry about pagination yet
	@items = Item.find_with_some_custom_method(@some_variable)

	# step 3: create a Paginator, the second variable has to be the
number of ALL items on all pages
	@item_pages = Paginator.new(self, @items.length, items_per_page, page)

	# step 4: only send a subset of @items to the view
	# this is where the magic happens... and you don't have to do
another find
	@items = @items[ offset..(offset + items_per_page - 1)]

end


HTH,
Kevin S.
John D. (Guest)
on 2005-12-20 01:04
(Received via mailing list)
Kevin S. wrote:
>     items_per_page = 20
>
>     # step 4: only send a subset of @items to the view
>     # this is where the magic happens... and you don't have to do
> another find
>     @items = @items[ offset..(offset + items_per_page - 1)]
>
> end

I suppose this is ok for small result sets, but the major problem with
this approach is that for pagination of larger sets of data, this is
going to be extremely inefficient.  The way the rails paginator works is
it gets a count of ALL the records, but then only selects what is going
to be displayed using the sql 'LIMIT' clause.

John
This topic is locked and can not be replied to.