Created
March 17, 2015 05:54
-
-
Save trmcnvn/132c4c5a68d1c19996e4 to your computer and use it in GitHub Desktop.
This file contains 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
# Faster random records | |
module ActiveRecord | |
class Base | |
def self.random(limit = 1) | |
if (total = count) > 0 | |
highest_possible_offset = [0, total - limit].max | |
offset = [rand(total), highest_possible_offset].min | |
num = [limit, total].min | |
offset(offset).limit(num) | |
else | |
self | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment