How to join SUM in ActiveRecord

Say I have two simple models

project
   t.string :title

vote
   t.references :project
   t.integer :value

When I do a cycle of all projects, I also want to include the sum of all votes, because to do

projects = Project.all

foreach project in projects
    sum = project.votes.sum(:value)
    ...

ineffective.

Is there a way to do this without manually writing SQL? Sort of

SELECT p.*, SUM(v.value)
FROM projects p
LEFT JOIN votes v
ON v.project_id = p.id
GROUP BY p.id
+3
source share
1 answer

If this is often calculated, you are probably better off storing summary statistics in a project record (total_votes). You can update the details of each vote or update it using the cron job.

I think you are looking for the following:


@totals = Vote.sum(:value,:group=>:project_id)
@projects = Project.find(:all)

then


<%=h @project.title %> has <%= @totals[@project.id] %> votes.
+5
source

Source: https://habr.com/ru/post/1716320/


All Articles