Last active
December 5, 2024 15:04
-
-
Save nsmmrs/13a87fdfb969fcf30e40668a74d35c39 to your computer and use it in GitHub Desktop.
Rails Model "random_record" Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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".