user1179942
user1179942

Reputation: 391

ActiveRecord::Relation query for grouped objects

I have three models User, Subject and 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

User can have several grades for the same subject.

On the user's page, I would like to display his average and maximum grade for each subject. What is the best way to accomplish 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 maximum and average, but I don't know how to get ActiveRecord::Relation-object for each group of grades.

Upvotes: 3

Views: 156

Answers (1)

jdoe
jdoe

Reputation: 15781

I guess you need something like:

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

Upvotes: 3

Related Questions