Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Created September 7, 2010 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeincontext/569098 to your computer and use it in GitHub Desktop.
Save codeincontext/569098 to your computer and use it in GitHub Desktop.
The cleanest way of selecting a random record from an ActiveRecord table.
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
@codeincontext
Copy link
Author

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.

@codeincontext
Copy link
Author

Now you can add conditions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment