Re: custom find methods and pagination


#1

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. :slight_smile:

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.


#2

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