Randomly sample from ActiveRecord collection object?

Viewed 302

Suppose we have something of class

@physician.availabilities.class
=> Availability::ActiveRecord_Associations_CollectionProxy

@physician.availabilities.length
=> 72

How can we randomly sample records from this object?

E.g. this looks promising

@physician.availabilities.sample(5)

execept that

@physician.availabilities.sample(5).class
=> Array

whereas I want to retrain an ActiveRecord object (so I can .save the random sample but not the others)

1 Answers

You could do this in two queries.

ids = @physician.availabilities.sample(5).pluck(:id)
@physician.availabilities.where(id: ids)

This is also possible using Postgres with RANDOM

@physician.availabilities.order('RANDOM()').limit(5)

...or if you are into MySQL with RAND

@physician.availabilities.order('RAND()').limit(5)
Related