Created
September 7, 2010 21:05
-
-
Save codeincontext/569098 to your computer and use it in GitHub Desktop.
The cleanest way of selecting a random record from an ActiveRecord table.
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
module ActiveRecord | |
class Base | |
def self.random(conditions = nil) | |
c = count(:conditions=>conditions) | |
unless c == 0 | |
first(:conditions=>conditions, :offset =>rand(c)) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now you can add conditions