paginate hash using pagy gem

Viewed 698

I have a Products table that stores products for a shop and one of the entries of the products is vendor. So multiple products will have the same vendor (i.e Nike). I also have a Sales table that has products. I want to calculate the number of sales per product vendor.

My code will return a hash where the key is vendor and the value is the number of sales like this:

{
  "Adidas":40,
  "Nike":34,
  "Reebok":23,
  ...
}

The problem with this is that the number of vendors can get huge and I'd only want to display lets say 50 at a time. What's the best way to implement pagination on this hash? I'm using ruby on rails with a react front end (react on rails). I'd prefer using the pagy gem based on its performance compared to other pagination gems.

1 Answers

based on the documentation https://ddnexus.github.io/pagy/extras/array, you can paginate an array with pagy_array, like this:

@pagy_a, @items = pagy_array(hash.to_a, items: 50)

before that you should uncomment

require 'pagy/extras/array' 

in pagy.rb file, and add

include Pagy::Backend

to your controller

I hope that help you

Related