Skip to content

Instantly share code, notes, and snippets.

@timfjord
Last active January 3, 2016 11:49
Show Gist options
  • Save timfjord/8458673 to your computer and use it in GitHub Desktop.
Save timfjord/8458673 to your computer and use it in GitHub Desktop.
def total_by(obj, date)
if obj.is_a? String
group_by = obj
filter_by = false
else
filter_by = obj.class.model_name
group_by = opposite_association(name).to_s
end
query = scoped.where(date: date.beginning_of_month..date.end_of_month)
query = query.where(filter_by.foreign_key => obj.id) if filter_by
result = query.sum(:time, group: group_by.foreign_key)
list = group_by.pluralize.to_sym
if obj.respond_to? list
obj.send(list).each do |item|
result[item.id] = 0 unless result.key? item.id
end
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment