Created
December 28, 2013 21:51
-
-
Save benshimmin/8164688 to your computer and use it in GitHub Desktop.
Use scoped queries to select N records at random with ActiveRecord
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
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