This one is short but not something I immediately thought of. It doesn’t rely on an ActiveRecord abstraction, but I originally thought it would need to, so the title is to save future Web searchers.
The idea is that you want to create a list of all the Users, but ordered randomly. It turns out that it’s just this (Postgre)SQL:
SELECT * FROM users ORDER BY random();
So, in Rails:
User.find(:all, :order => 'random()')
Update: Check out the plugin based on this, and the drawbacks to this.
2 Comments
for mysql
User.find(:all, :order => ‘rand()’)
Hello,
your method is very good if you want to select all the rows from the table in random order.
It wouldn’t do very good if you wanted to get just 1 row or even 10 out of 10000.
Here’s a nice way to get just 1 random row:
http://robzon.aenima.pl/2007/12/selecting-random-row-from-table.html
cheers!