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`).
While not the fastest solution, I like the brevity of:
User.ids.sample(10)
The
.ids
method yields an array of User IDs and.sample(10)
picks 10 random values from this array.I think the best solution is really ordering randomly in database. But if you need to avoid specific random function from database, you can use
pluck
andshuffle
approach.For one record:
For more than one record:
Here's a quick solution.. currently using it with over 1.5 million records and getting decent performance. The best solution would be to cache one or more random record sets, and then refresh them with a background worker at a desired interval.
Created
random_records_helper.rb
file:in the controller:
This is much quicker than the
.order("RANDOM()").limit(10)
method - I went from a 13 sec load time down to 500ms.I would suggest making this a scope as you can then chain it:
As the random function could change for different databases, I would recommend to use the following code:
Of course, this is useful only if you're looking for only one record.
If you wanna get more that one, you could do something like:
The
- 10
is to assure you get 10 records in case rand returns a number greater than count - 10.Keep in mind you'll always get 10 consecutive records.
You'll want to use the
order
andlimit
methods instead. You can get rid of theall
.For PostgreSQL and SQLite:
Or for MySQL: