Skip to content

Instantly share code, notes, and snippets.

@jonahb
Last active December 12, 2015 05:19
Show Gist options
  • Save jonahb/4720818 to your computer and use it in GitHub Desktop.
Save jonahb/4720818 to your computer and use it in GitHub Desktop.
class ActiveRecord::Relation
# Returns no more than n records, chosen at random
#
# @param [Integer] n
# @return [ActiveRecord::Base, nil]
# When n == 1
# @return [Array]
# When n > 1
#
def find_random( n = 1 )
raise ArgumentError if n < 1
sql = select( primary_key ).to_sql
ids = connection.
execute( sql ).
to_a.
shuffle.
take( n ).
map( &:first )
find( *ids )
end
end
class ActiveRecord::Base
def self.find_random( n = 1 )
scoped.find_random( n )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment