Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum all properties of a nested collection?

Given I got User.attachments and Attachment.visits as an integer with the number count.

How can I easily count all the visits of all images of that user?

like image 418
Martin Avatar asked Mar 08 '11 14:03

Martin


2 Answers

Use ActiveRecord::Base#sum:

user.attachments.sum(:visits)

This should generate an efficient SQL query like this:

SELECT SUM(attachments.visits) FROM attachments WHERE attachments.user_id = ID
like image 154
tokland Avatar answered Oct 05 '22 10:10

tokland


user.attachments.map{|a| a.visits}.sum
like image 45
Calin Avatar answered Oct 05 '22 08:10

Calin