there is a wonderful command for random uses, called, (surprisingly)
RAND().
so, if i am correct, you can go like this:
def anaction
@variable = MyModel.find(:first, :order => [“RAND()”]) and it should
bring forth
end # the first object it finds, in a random order.
RAND() is a pricey option though as it’s going to select every row in
your
table, assign it a random value, then sort it on that value. Then
return
the first record.
Might be a lot faster to find the maximum id, then use ruby to generate
a
random value between 1 and max_id, then so something like:
MyModel.find(:first, :conditions => [“id >= ?”, random_id])
Or something along those lines.
On my end_users table which has about 80,000 rows, the rand() takes
about
1.60 seconds. The second query takes 0.00… not super scientific, but
still…
mysql> explain select * from end_users order by rand() limit 1;
±—±------------±----------±-----±--------------±-----±--------±-----±------±--------------------------------+
| id | select_type | table | type | possible_keys | key | key_len |
ref | rows | Extra |
±—±------------±----------±-----±--------------±-----±--------±-----±------±--------------------------------+
| 1 | SIMPLE | end_users | ALL | NULL | NULL | NULL |
NULL | 80525 | Using temporary; Using filesort |
±—±------------±----------±-----±--------------±-----±--------±-----±------±--------------------------------+
1 row in set (0.00 sec)
mysql> explain select * from end_users where id >= 12345 limit 1;
±—±------------±----------±------±--------------±--------±--------±-----±------±------------+
| id | select_type | table | type | possible_keys | key | key_len
| ref | rows | Extra |
±—±------------±----------±------±--------------±--------±--------±-----±------±------------+
| 1 | SIMPLE | end_users | range | PRIMARY | PRIMARY | 4
| NULL | 65667 | Using where |
±—±------------±----------±------±--------------±--------±--------±-----±------±------------+