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?
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)
Just sort them randomly in sql and take the first 13. so do:
c.photos.order("RAND()").limit(13)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With