19

I am iterating through a large array of model objects and need to paginate for performance/memory reasons.

I want to do something like this:

for i in 1..Person.num_pages
  Person.page(i).each do
    # work
  end
end

Obviously I can get the count and do the math myself, but is there an equivalent of num_pages? Or is there a more elegant way of doing this altogether?

keithgaputis
  • 731
  • 2
  • 6
  • 11

1 Answers1

42

Use total_pages.

Yes, you can use total_pages to retrieve the total number of pages in your model.

For example:

@blog_entries = Blog.all.page(1).per(20)
puts "total pages: #{@blog_entries.total_pages}"

Version < 0.14.0

Previous to version 0.14.0, the method was called num_pages instead of total_pages.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Edmar Miyake
  • 12,047
  • 3
  • 37
  • 38
  • 6
    `num_pages` has been renamed to `total_pages` in version 0.14.0 ([commit](https://github.com/amatsuda/kaminari/commit/e79935c2d596e165be566f6d92eed8d5acd6a843)) – ciastek Sep 06 '13 at 13:58
  • 1
    If you are using the default `per`, just do `Blog.all.page(1).total_pages` – Adam Grant Apr 13 '15 at 15:20
  • Doc "Module: Kaminari::PageScopeMethods": https://www.rubydoc.info/github/amatsuda/kaminari/master/Kaminari/PageScopeMethods – Pascal Jun 09 '18 at 13:26