Last active
August 29, 2015 14:08
-
-
Save iheanyi/e63c0a16fd57dce8ce85 to your computer and use it in GitHub Desktop.
Counter Caches and HABTM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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. :/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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