Dan Benjamin
Dan Benjamin

Reputation: 900

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?

Upvotes: 0

Views: 323

Answers (1)

wintermeyer
wintermeyer

Reputation: 8318

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.

Upvotes: 2

Related Questions