views:

136

answers:

2

I need to find all records for a particular resource and display them in a random order, but with consistent pagination (you won't see the same record twice if you start paging). The display order should be randomized each time a user visits a page. I am using will_paginate. Any advice?

+1  A: 

If you're using a database such as MySQL that has a randomize function such as RAND(), you can just add that to your pagination query like so:

Resource.paginate( ... :order => "RAND()" ... )

Check out some of the comments here regarding performance concerns: https://rails.lighthouseapp.com/projects/8994/tickets/1274-patch-add-support-for-order-random-in-queries

Beerlington
This won't work. When changing pages (i.e. 1 to 2) the query is run a second time, and it is possible to have a duplicate entry appear (an entry that was on page 1 also appearing on page 2).
Kevin Sylvestre
I thought you meant you just wanted the entries on each page to be random. You could store the previously viewed pages in a session array and filter them out on the next request, but that seems really hacky and brittle.
Beerlington
Yeah, that doesn't seem like a very good solution. I'm just a bit surprised something better doesn't exist. I've seen it implemented before in Ruby on Rails apps like http://sortfolio.com/.
Kevin Sylvestre
I checked out Sortfolio and their listings are not random. If you refresh the page a few times, you will see the listings in the same order, just staring from a different offset. It's almost like going around in a circle, you can start at any point, but if you go around it in the same direction, you will always pass by the same points in a consistent order.
Beerlington
Thanks for the note. I didn't realize the site wasn't using random.
Kevin Sylvestre
+1  A: 

This is not standard to my knowledge. I can see a use for this for instance for online tests.

I would suggest using a list per session/user. So when a user first goes to the page, you determine a list of ID's, in a random order, and all consecutive views you will use this list to show the correct order for that user/session.

I hope that the amount of rows is limited, and then this would make sense, for instance for tests. Also, when a user would leave a test before finishing it completely, she could continue where he left off. But maybe that is not relevant for you.

Hope this helps.

nathanvda
Thanks for the response. I am not sure that I will be able to use a session (as it is per page view) but I might be able to embed the list of IDs in a form. Seems like pulling teeth right now.
Kevin Sylvestre