Skip to content

Instantly share code, notes, and snippets.

@iheanyi
Last active August 29, 2015 14:08
Show Gist options
  • Save iheanyi/e63c0a16fd57dce8ce85 to your computer and use it in GitHub Desktop.
Save iheanyi/e63c0a16fd57dce8ce85 to your computer and use it in GitHub Desktop.
Counter Caches and HABTM
class Course < ActiveRecord::Base
belongs_to :department, counter_cache: true
has_many :sections
has_many :professors, -> { uniq }, through: :sections
has_many :course_attributes
has_many :cattributes, through: :course_attributes, class_name: "Attribute"
validates :department, presence: true
end
[5] pry(main)> Professor.reset_counters(4, :sections)
Professor Load (1.1ms) SELECT "professors".* FROM "professors" WHERE "professors"."id" = $1 LIMIT 1 [["id", 4]]
(0.4ms) SELECT COUNT(*) FROM "sections" WHERE "sections"."professor_id" = $1 [["professor_id", 4]]
(0.7ms) UPDATE "professors" SET "courses_count" = 12 WHERE "professors"."id" = 4
=> true
# Notice how it is updating the Courses Count, when I want this to be sections_count updated. :/
class Professor < ActiveRecord::Base
#include ActiveModel::Serialization
has_many :section_professors
has_many :sections
has_many :courses, -> { uniq }, :through => :sections
def after_save
update_counter_cache
end
def after_destroy
update_counter_cache
end
def update_counter_cache
#self.courses_count = self.courses.count
Professor.update_counters(self.id, :courses_count => self.courses.count)
self.save!
end
#counter_culture [:course]
#counter_culture [:section]
end
class Section < ActiveRecord::Base
belongs_to :course, counter_cache: true
# Setup Professor Sections Counter
belongs_to :professor, counter_cache: true
def after_save
self.update_counter_cache
end
def after_destroy
self.update_counter_cache
end
def update_counter_cache
self.professor.update_counter_cache
self.save!
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment