DoubleD
DoubleD

Reputation: 183

Sum of values in a has_many through - belongs_to association

In a Ruby on Rails 6.1 project I have Users that can pick a list of Activities. Each Activity has a value. I would like to get the total sum for all the Activities selected by all Users.

My Models are:

class User < ApplicationRecord
  has_many :user_activities, dependent: :destroy
  has_many :activities, -> { distinct }, through: :user_activities
end
class Activity < ApplicationRecord
  has_many :user_activities, dependent: :destroy
  has_many :users, -> { distinct }, through: :user_activities
end
class UserActivity < ApplicationRecord
  belongs_to :user
  belongs_to :activity
end

As mentioned, in the schema, Activities has an integer field that I called value and each activity has a value selected to it.

I managed to get the sum of all of the selected activities by all users using the following code but I was wondering if there is a better way to do this.

total_value = 0
UserActivity.all.each do |selected_user_activity|
  total_value += selected_user_activity.activity.value
end

Upvotes: 1

Views: 400

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14890

This is simple if I understand you correctly.

sum_of_all_values = User.joins(:activities).sum('activities.value')

Upvotes: 2

Related Questions