neon neon - 1 year ago 116
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
is re-shuffled on each pagination request, causing duplicate records to be called. Is there any way to prevent this kind of duplication?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download