User.find(:all, :order => "RANDOM()", :limit => 10)
was the way I did it in Rails 3.
User.all(:order => "RANDOM()", :limit => 10)
is how I thought Rails 4 would do it, but this is still giving me a Deprecation warning:
DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`).
You could call
.sample
on the records, like:User.all.sample(10)
For MYSQL this worked for me:
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
All other answers perform badly with large database, except this gem:
4.6ms
totally.User.order('RAND()').limit(10)
cost733.0ms
.offset
approach cost245.4ms
totally.User.all.sample(10)
approach cost573.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))
cost1384.0ms
gem: quick_random_records
only cost6.4ms
totally