Random record in ActiveRecord

Posted by astrofoo on Stack Overflow See other posts from Stack Overflow or by astrofoo
Published on 2010-05-02T02:11:52Z Indexed on 2010/05/02 2:17 UTC
Read the original article Hit count: 254

I'm in need of getting a random record from a table via ActiveRecord. I've followed the example from Jamis Buck from 2006.

However, I've also come across another way via a Google search (can't attribute with a link due to new user restrictions):

 rand_id = rand(Model.count)
 rand_record = Model.first(:conditions => [ "id >= ?", rand_id])

I'm curious how others on here have done it or if anyone knows what way would be more efficient.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord