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.
I use this so often from the console I extend ActiveRecord in an initializer - Rails 4 example:
I can then call
Foo.random
to bring back a random record.I haven't found an ideal way to do this without at least two queries.
The following uses a randomly generated number (up to the current record count) as an offset.
To be honest, I've just been using ORDER BY RAND() or RANDOM() (depending on the database). It's not a performance issue if you don't have a performance issue.
I'm brand new to RoR but I got this to work for me:
It came from:
How to randomly sort (scramble) an array in Ruby?
Benchmarking these two methods on MySQL 5.1.49, Ruby 1.9.2p180 on a products table with +5million records:
Offset in MySQL appears to be much slower.
EDIT I also tried
But I had to kill it after ~60 seconds. MySQL was "Copying to tmp table on disk". That's not going to work.