简体   繁体   中英

Rails - Query n random records from an association

I have two classes. User and Review (User has many reviews).

I am trying to find then best method to extract two random reviews from the association of User.reviews

I can use user.reviews.order("RANDOM()").limit(n) but if I'm not mistaken this will be very heavy on the DB if I have users with a large number of reviews...

I am using Postgres as my database.

Thoughts?

A database independent solution would be:

user.reviews.where(id: user.reviews.pluck(:id).sample(2))

I always prefer database independent solutions because otherwise it doesn't make sense to use ActiveRecord at all. Obviously this solution does two DB requests compared to your RANDOM() approach. Performance wise it is a tricky question because the database can cache these requests. It can not cache a RANDOM() request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM