I have a long association between Family
and Lesson
but I want to add a counter_cache so I can easily display family.lessons_count
on my Family index page.
Calling family.lessons.count
works fine but of course on the index page I’m calling it many times from the view causing far too many queries just for a count column in a table.
Where do I put the counter_cache column and how do I reference it in (which?) model?
(Setting up a separate counter_cache
for family.students_count
was easy because a student directly belongs_to
a family)
# family.rb
class Family < ActiveRecord::Base
has_many :students
has_many :school_classes, through: :students
has_many :lessons, through: :school_classes
...
end
# student.rb
class Student < ActiveRecord::Base
belongs_to :family, counter_cache: true # this one works fine
has_many :class_memberships
has_many :school_classes, through: :class_memberships
has_many :lessons, through: :school_classes
...
end
# school_class.rb
class SchoolClass < ActiveRecord::Base
has_many :class_memberships
has_many :students, through: :class_memberships
has_many :lessons
...
end
# lesson.rb
class Lesson < ActiveRecord::Base
belongs_to :school_class
has_many :students, through: :school_class
..
end
My app is still on Rails 3.2.14 so none of the new hotness here please