Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: get a specific number of random records

So, my app has Photos that belong to Collections. I want to be able to show 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)

This works, sort of. The problem is, if the collection doesn't have a lot more than 13 photos then it doesn't necessarily return 13 photos. I need to specifically get exactly 13 photos.

FWIW In the case of my app a Collection is only created by admins/mods, so we can enforce that no collection will have fewer than 13 photos. What I need is to be able to start making the selection of photos random once more than 13 are available.

How could I do this?

like image 485
Andrew Avatar asked Mar 17 '11 17:03

Andrew


2 Answers

You could first select 13 random associated photo IDs, then do a database query to fetch them:

c = Collection.first
random_ids = c.photo_ids.sort_by { rand }.slice(0, 13)
@photos = Photo.where(:id => random_ids)
like image 153
Kevin Qi Avatar answered Sep 27 '22 18:09

Kevin Qi


Just sort them randomly in sql and take the first 13. so do:

c.photos.order("RAND()").limit(13)
like image 36
Kyle d'Oliveira Avatar answered Sep 27 '22 19:09

Kyle d'Oliveira