Get random record using ActiveRecord
11 March 2022 (Updated 11 March 2022)
User.find(User.pluck(:id).sample)
This will fire off two SQL queries:
User Pluck (0.4ms) SELECT "users"."id" FROM "users"
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
Tagged:
Rails
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment