I don\'t know if I\'m just looking in the wrong places here or what, but does active record have a method for retrieving a random object?
Something like?
<
Strongly Recommend this gem for random records, which is specially designed for table with lots of data rows:
https://github.com/haopingfan/quick_random_records
Simple Usage:
@user = User.random_records(1).take
All other answers perform badly with large database, except this gem:
4.6ms totally.User.order('RAND()').limit(10) cost 733.0ms.offset approach cost 245.4ms totally.User.all.sample(10) approach cost 573.4ms.Note: My table only has 120,000 users. The more records you have, the more enormous the difference of performance will be.
UPDATE:
Perform on table with 550,000 rows
Model.where(id: Model.pluck(:id).sample(10)) cost 1384.0msgem: quick_random_records only cost 6.4ms totally