Skip to content

Instantly share code, notes, and snippets.

@nsmmrs
Last active December 5, 2024 15:04
Show Gist options
  • Save nsmmrs/13a87fdfb969fcf30e40668a74d35c39 to your computer and use it in GitHub Desktop.
Save nsmmrs/13a87fdfb969fcf30e40668a74d35c39 to your computer and use it in GitHub Desktop.
Rails Model "random_record" Helper
class ApplicationRecord
def self.random
max = maximum(primary_key)
return if max.nil?
find_random = lambda do
order(primary_key).find_by(primary_key => (rand(max)..))
end
record = find_random.call
record = find_random.call until record.present?
record
end
end
@nsmmrs
Copy link
Author

nsmmrs commented Apr 22, 2023

I've only ever used this as a toy method in dev/test environments, but I could see it being useful in production environments that have buttons like "Play a Random Song".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment