Skip to content

Instantly share code, notes, and snippets.

@griffithac
Created June 9, 2012 20:52
Show Gist options
  • Save griffithac/2902563 to your computer and use it in GitHub Desktop.
Save griffithac/2902563 to your computer and use it in GitHub Desktop.
Sum and Average Virtual Attributes in ActiveRecord
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