Created
May 7, 2016 17:17
-
-
Save JeffCohen/32c7c08f3b0c71cd6087a86256b57347 to your computer and use it in GitHub Desktop.
ActiveRecord::sample
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
# 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