kongzi
kongzi

Reputation: 5

Rails: Size is not working on a has_many relationship

I have two models, Student and Absence, with the relationship:

class Student < ActiveRecord::Base
  has_many :absences

class Absence < ActiveRecord::Base
  belongs_to :student

I want to see how many absences have been logged for each student, and show that total on the student's #show page. In the console, I'm able to query this by calling:

a = Student.find(1)
a.absences.size 

However, I can't seem to get it to work in the app itself. Would the preferred way of querying this in the app be in the model or the controller?

Upvotes: 0

Views: 85

Answers (1)

potashin
potashin

Reputation: 44581

This will never work, since you are calling association on the model, not instance. At first you should fetch a student and then count associated records:

Student.find(<id here>).absences.size

To aggregate this information for all students, you can add absence_count attribute accessor in Student model:

attr_accessor :absence_count

and then do something like this:

Student.includes(:absences).each{|s| s.absence_count = s.absences.size}

If you just need to output it in the view, then you can try the following:

Student.includes(:absences).each do |student|
  puts student.absences.size
end

Upvotes: 1

Related Questions