Skip to content

Instantly share code, notes, and snippets.

@leejarvis
Created June 26, 2012 16:10
Show Gist options
  • Save leejarvis/2996763 to your computer and use it in GitHub Desktop.
Save leejarvis/2996763 to your computer and use it in GitHub Desktop.
module SqlRandom
module Relation
def shuffled
rand_cmd = if connection.adapter_name =~ /mysql/i
'rand()'
else
'random()'
end
clone.order(rand_cmd)
end
end
module Base
def shuffled
relation.shuffled
end
def random
shuffled.limit(1).first
end
end
end
class ActiveRecord::Relation
include SqlRandom::Relation
end
class ActiveRecord::Base
extend SqlRandom::Base
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment