6

enter image description here

This is my pagination, I want to limit the number of pages to 10, for example, to don't have the same problem as in the picture.

How can I do it using will_paginate gem?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Loenvpy
  • 899
  • 1
  • 10
  • 30

3 Answers3

15

The following command:

<%= will_paginate @yourwhatevers, inner_window: 3, outer_window: 1 %>

accomplishes this. Let's say you are on page 15 of 36, you will get:

Previous 1 2 ... 12 13 14 15 16 17 18 .. 35 36 Next

inner_window, in other words how many to the right and left from current page, defaults to 4, but for better, you could make it 1 or 2. outer_window defaults to 1, so my line above could not contain it at all

Ruby Racer
  • 5,690
  • 1
  • 26
  • 43
  • inner_window: 1, outer_window: 0 solve my problem. I have a problem with mobile devices like iPhone can't show the previous and next button because of too many pages on paginate section can't fit on mobile devices. – Anjan Biswas Aug 18 '21 at 04:52
4

There is quite a few ways to do it depending on that you want to do. Check out this answer:

Limit number of pages in will_paginate

One example with limiting it to 100 entries with 10 on a page (hence 10 pages)

@posts = Post.paginate(:page => params[:page], :per_page => 10, 
                       :total_entries => 100)
Community
  • 1
  • 1
ChrisBarthol
  • 4,871
  • 2
  • 21
  • 24
3

You could limit the amount of results to be 10 times your page size:

MyModel.limit(300).paginate(page: params[:page])

That would mean you couldn't return any more than 300 results and therefore no more than 10 pages worth.

Alternatively you could explore some of the will_paginate rendering options. You can configure the amount of pages display at the end of the pagination and around the current page - or even remove the page numbers altogether. For example:

will_paginate @results, inner_window: 1, outer_window: 1

will show Previous | 1 | ... | 9 | ... | 16 | Next for the example in the question.

Shadwell
  • 34,314
  • 14
  • 94
  • 99