简体   繁体   中英

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

This is simple if I understand you correctly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM