neon neon - 3 months ago 16
MySQL Question

Paginating a shuffled ActiveRecord query

I am attempting to paginate a shuffled ActiveRecord query. The syntax for doing this using the Kaminari gem is:

@users = Kaminari.paginate_array(User.all.shuffle).page(params[:page]).per(20)


The issue with this is that
User.all
is re-shuffled on each pagination request, causing duplicate records to be called. Is there any way to prevent this kind of duplication?

Answer

You need to pass seed for rand between queries

params[:seed] ||= Random.new_seed
srand params[:seed].to_i
@users = Kaminari.paginate_array(User.all.shuffle).page(params[:page]).per(20)

And in view add params[:seed] to all kaminari links to pages

Comments