开发者

Rails: get a specific number of random records

开发者 https://www.devze.com 2023-02-18 14:57 出处:网络
So, my app has Photos that belong to Collections. I want to be able to show 13 photos from a specific c开发者_如何学Collection on a page.

So, my app has Photos that belong to Collections. I want to be able to show 13 photos from a specific c开发者_如何学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)


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:

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))
0

精彩评论

暂无评论...
验证码 换一张
取 消