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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With