Get random collection of records with Active Record
28 April 2022 (Updated 28 April 2022)
Suppose you have a Reminder
model and you want to return x
number of records at random. Something like this:
Reminder.sample # 1 record
Reminder.sample(5) # 5 records
Here’s how:
class Note
def self.sample(count = 1)
find(pluck(:id)).sample(count)
end
end
This will produce two SQL queries. Something like:
Reminder Pluck (1.2ms) SELECT "reminders"."id" FROM "reminders"
Reminder Load (0.4ms) SELECT "reminders".* FROM "reminders" WHERE "reminders"."id" IN ($1, $2) [["id", 114], ["id", 118]]
Tagged:
Rails
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment