ActiveRecord :: Relationship request for grouped objects

I have three models User, Subjectand Grade.

class User< ActiveRecord::Base
  has_many :grades
end

class Subject < ActiveRecord::Base
  has_many :grades
end

class Grade < ActiveRecord::Base
  belongs_to :user
  belongs_to :subject
end

A user may have several ratings for the same subject.

On the user's page, I would like to show its evaluation averageand maximumfor each object. What is the best way to achieve it?

User: Qwerty
Grades:
-------------------------------
subject       average   maximum
-------------------------------
"subject_1"   56        97
"subject_2"   45        85

As far as I know, ActiveRecord :: Relation has special methods for maximumand average, but I do not know how to get a ActiveRecord::Relation-object for each class group.

+3
source share
1 answer

I think you need something like:

user.grades.joins(:subject).
  group(:subject_id).
  select(['MAX(grades.grade) as max', 'AVG(grades.grade) as avg', subjects: :name])
+3
source

All Articles