Rails: get a certain amount of random entries

So, my application has photos belonging to the collections. I want to be able to display 13 photos from a specific collection on a page.

I tried this:

c = Collection.first @photos = c.photos.offset(rand(c.photos.count)).limit(13) 

It works, sort of. The problem is that if the collection does not have more than 13 photos, then it does not necessarily return 13 photos. I need to specifically receive exactly 13 photos.

FWIW. In the case of my application, the collection is created only by administrators / mods, so we can ensure that the collection does not have at least 13 photos. I need to be able to make the selection of photos random when more than 13 are available.

How can i do this?

+7
source share
3 answers

First you can select 13 random associated photo identifiers, then query the database to retrieve them:

 c = Collection.first random_ids = c.photo_ids.sort_by { rand }.slice(0, 13) @photos = Photo.where(:id => random_ids) 
+13
source

Just sort them arbitrarily in sql and take the first 13. like this:

 c.photos.order("RAND()").limit(13) 
+6
source

Here's a quick fix. He currently uses it with over 1.5 million records and is getting decent performance. The best solution would be to cache one or more sets of random records, and then update them using the desktop at the right interval.

The random_records_helper.rb file is created:

 module RandomRecordsHelper def random_user_ids(n) user_ids = [] user_count = User.count n.times{user_ids << rand(1..user_count)} return user_ids end 

in the controller:

 @users = User.where(id: random_user_ids(10)) 
-one
source

All Articles