I want to give users the ability to page through my blog posts in random order.
I can't implement it like this:
@posts = Post.paginate :page => params[:page], :order => 'RANDOM()'
since the :order
parameter is called with every query, and therefore I risk repeating blog posts.
What's the best way to do this?
You could :order => RANDOM() on your original query that populates @posts, and then when you paginate, don't specify the order.
RAND accepts a seed in MySQL:
From the MySQL docs:
Other databases should have similar functionality.
If you use the SAME seed each time you call RAND, the order will be consistent across requests and you can paginate accordingly.
You can then store the seed in the user's session - so each user will see a set of results unique to them.
To avoid each page (generated from a new request) potentially having a repeated post you'll need to store the order of posts somewhere for retrieval over multiple requests.
If you want each user to have a unique random order then save the order in a session array of IDs.
If you don't mind all users having the same random order then have a position column in the posts table.
Create a named scope on your Post model that encapsulates the random behaviour:
Your
PostsController
code then becomes: