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 |
Now you can add conditions
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So this is a snippet I use in script/console when playing around/testing. It extends ActiveRecord::Base which allows me to do Message.random.resend_notification et cetera. Use it in an initializer, or alternatively, I've written it into a plugin.
I prefer the way this works because it is very clean and efficient. Other solutions of getting a random record either require loading a list of all IDs in the table to choose from, or pick a random number, then check that a record of that ID exists in the table. Both seem silly to me.