Skip to content

Instantly share code, notes, and snippets.

@pgeraghty
Created February 13, 2013 22:03
Show Gist options
  • Save pgeraghty/4948780 to your computer and use it in GitHub Desktop.
Save pgeraghty/4948780 to your computer and use it in GitHub Desktop.
ActiveRecord::Base.sample hack for choosing a random model instance - useful for tests and seeding
module ActiveRecord
class Base
# Use like User.sample or User.pluck(:id).sample
def self.sample
order('RAND()').first rescue nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment