Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Created September 7, 2010 21:05
Show Gist options
  • 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

Now you can add conditions

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