Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Created December 28, 2013 21:51
Show Gist options
  • Save benshimmin/8164688 to your computer and use it in GitHub Desktop.
Save benshimmin/8164688 to your computer and use it in GitHub Desktop.
Use scoped queries to select N records at random with ActiveRecord
class Foo < ActiveRecord::Base
scope :random_n, -> (n) { limit(n).order("RANDOM()") }
end
Foo.random_n(5) # -> five randomly chosen Foos
# For extra points, put this sort of thing into a Concern.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment