Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly sample from ActiveRecord collection object?

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)

like image 241
stevec Avatar asked Aug 06 '26 11:08

stevec


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)
like image 80
Eyeslandic Avatar answered Aug 09 '26 05:08

Eyeslandic