Skip to content

Instantly share code, notes, and snippets.

@JeffCohen
Created May 7, 2016 17:17
Show Gist options
  • Save JeffCohen/32c7c08f3b0c71cd6087a86256b57347 to your computer and use it in GitHub Desktop.
Save JeffCohen/32c7c08f3b0c71cd6087a86256b57347 to your computer and use it in GitHub Desktop.
ActiveRecord::sample
# Example usage:
# Product.sample => returns a Product
# Product.sample(3) => returns an array of 3 products
# Product.sample(3, true).order('title') => allows chaining
class ActiveRecord::Base
# Choose rows at random
def self.sample(n = 1, keep_as_relation = false)
rows = offset(rand(0...(count-n-1))).limit(n)
rows = rows.first(n) unless keep_as_relation
rows = rows.first unless keep_as_relation || n != 1
return rows
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment