2

I am trying to cache requests that come in for Products. I am using the Kaminari gem for pagination but for some reason I cannot see all the products on my view page. It seems to only take the top 25 and list those.

def index

cache_key = Product::CACHE_KEY_PREFIX + params.map{|k,v| "[#{k}-#{v}]"}.join("-")

@products = Rails.cache.fetch(cache_key, expires_in: 30.minutes) do
  search_params = params.permit(:product_type,:format).to_h.symbolize_keys
  if search_params[:product_type]
    products = Product.by_product_type(params[:product_type])
  elsif params[:filters].present?
    filters = params[:filters].try(:symbolize_keys)
    products = Product.where(filters)
  else
    products = Product.all
  end
  byebug #at this point products count is 43
  products = products.page(params[:page])
  byebug #count is now 25
  @products = Kaminari.paginate_array(products.to_a).page(params[:page])
  @products #count is 25
end

respond_to do |format|
  format.html
  format.json
end

end

syed zaidi
  • 127
  • 1
  • 10
  • `Product.all` returns all `Products`, when you `.page(params[:page])` it is expected to return only the page requested by `params[:page]` that's why count becomes 25. Am I losing something? – Lucas Wieloch Sep 18 '18 at 19:59
  • Yeah, you're right. Sorry I am still learning. I took out that line and now it is working fine. – syed zaidi Sep 18 '18 at 20:09

3 Answers3

1

You need to change this .

@products = Kaminari.paginate_array(products.to_a).page(params[:page])

to this:

@products = Kaminari.paginate_array(products.to_a).page(params[:page]).per(products.count)

The default per size is 25 if you do not specify the size.

ruby_newbie
  • 3,190
  • 3
  • 18
  • 29
0

From docs.

You can configure the following global default values by overriding these values using Kaminari.configure method.

config.default_per_page = 100      # 25 by default

There's a handy generator that generates the default configuration file into config/initializers directory. Run the following generator command, then edit the generated file.

rails g kaminari:config
Sergii Chub
  • 107
  • 1
  • 3
0

In the config/initializers/kaminari_config.rb file, add this:

# frozen_string_literal: true

Kaminari.configure do |config|
  config.default_per_page = 100
  # config.max_per_page = nil
  # config.window = 4
  # config.outer_window = 0
  # config.left = 0
  # config.right = 0
  # config.page_method_name = :page
  # config.param_name = :page
  # config.max_pages = nil
  # config.params_on_first_page = false
end

And you can change also the other default settings there.

Olivier Girardot
  • 389
  • 4
  • 16