Created
June 9, 2012 20:52
-
-
Save griffithac/2902563 to your computer and use it in GitHub Desktop.
Sum and Average Virtual Attributes in ActiveRecord
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
class ActiveRecord::Base | |
# Totals the virtual attributes of a collection | |
def self.vsum collection, v_attr | |
total = 0 | |
collection.each { |collect| total += collect.method(v_attr.to_s).call } | |
return total | |
end | |
# Avarages the virtual attributes of a collection | |
def self.vavg collection, v_attr | |
total = 0 | |
count = 0 | |
collection.each { |collect| total += collect.method(v_attr.to_s).call; count += 1 } | |
return total / count | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment