-
-
Save leemour/ea15148bc95ea31f3a1a to your computer and use it in GitHub Desktop.
Rails 4 cache_counter for has_and_belongs_to_many relationship
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
## I imagine this could be done in the migration, but it was giving me problems so I moved it to the model | |
## and just did it on the command line | |
> Tag.reset_questions_count |
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 AddQuestionsCounterToTags < ActiveRecord::Migration | |
def up | |
add_column :tags, :questions_count, :integer, default: 0, null: false | |
end | |
def down | |
remove_column :tags, :questions_count | |
end | |
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 Question < ActiveRecord::Base | |
## the validates_tag method is just to prevent duplicate tags being added to the db - not fully necessary for this exercise, | |
## but I figured I would leave it just in case | |
has_and_belongs_to_many :tags, before_add: :validates_tag | |
after_create :increment_tags_counter | |
before_destroy :decrement_tags_counter | |
protected | |
def validates_tag(tag) | |
self.tags.include? tag | |
end | |
def increment_tags_counter | |
self.tags.each {|t| t.increment!(:questions_count) } | |
end | |
def decrement_tags_counter | |
self.tags.each {|t| t.decrement!(:questions_count) } | |
end | |
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 Tag < ActiveRecord::Base | |
has_and_belongs_to_many :questions, -> { uniq } | |
def self.reset_questions_count | |
Tag.find_each do |t| | |
t.update(questions_count: t.questions.count) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment