3

COUNT query to find out total_count sometimes very slow. But if I am caching values of items_amount or such field in model I want to use it for kaminari pagination.

EXAMPLE: I have model

Category (:id, :title, :items_amount)

And then on show view I want to

<%= paginate @items, total_count: @category.items_amount %>

So like paginate_array, but in paginate. It is very useful for perfomance.

Is there a feature like this or how I can add it?

Like will_paginate gem, where we can do it like this .paginate(page: params[:page], per_page: 72, total_entries: @category.items_amount)

2 Answers2

2

Kaminari just calls the total_count method on @items in order to get the count. By default this does the SELECT count(*) ... query but you could decorate @items to be something that provides your cached count.

If you are just generating page links though then paginate will take a total_pages option. By providing the page count it means that the paginate call doesn't need to get the total count. (I can't find that option explicitly documented but it is in the code and I've tested using it).

paginate @items, total_pages: @cached_page_count

@cache_page_count might have a value like (@category.item_amount / 30.0).ceil in order to get the correct page count with 30.0 being your page size.

Shadwell
  • 34,314
  • 14
  • 94
  • 99
0

I think they answer this really well in their gems readme? https://github.com/kaminari/kaminari

You can do this on controller level using paginates_per to set the limit on each page and max_paginates_per to set the limit of pages?

TTD
  • 301
  • 1
  • 7