Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the 'Rails 4 Way' of finding some number of random records?

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`).
like image 471
justindao Avatar asked Jun 28 '13 20:06

justindao


3 Answers

You'll want to use the order and limit methods instead. You can get rid of the all.

For PostgreSQL and SQLite:

User.order("RANDOM()").limit(10)

Or for MySQL:

User.order("RAND()").limit(10)
like image 181
Dylan Markow Avatar answered Nov 10 '22 23:11

Dylan Markow


As the random function could change for different databases, I would recommend to use the following code:

User.offset(rand(User.count)).first

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:

User.offset(rand(User.count) - 10).limit(10)

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.

like image 40
maurimiranda Avatar answered Nov 10 '22 23:11

maurimiranda


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 and shuffle approach.

For one record:

User.find(User.pluck(:id).shuffle.first)

For more than one record:

User.where(id: User.pluck(:id).sample(10))
like image 23
Prodis Avatar answered Nov 11 '22 01:11

Prodis