Thing.first(:order => "RANDOM()") # For MySQL :order => "RAND()", - thanx, @DanSingerman
# Rails 3
Thing.order("RANDOM()").first
or
Thing.first(:offset => rand(Thing.count))
# Rails 3
Thing.offset(rand(Thing.count)).first
Actually, in Rails 3 all examples will work. But using order RANDOM
is quite slow for big tables but more sql-style
UPD. You can use the following trick on an indexed column (PostgreSQL syntax):
select *
from my_table
where id >= trunc(
random() * (select max(id) from my_table) + 1
)
order by id
limit 1;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…