Skip to content

Instantly share code, notes, and snippets.

@trmcnvn
Created March 17, 2015 05:54
Show Gist options
  • Save trmcnvn/132c4c5a68d1c19996e4 to your computer and use it in GitHub Desktop.
Save trmcnvn/132c4c5a68d1c19996e4 to your computer and use it in GitHub Desktop.
# 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