Skip to content

Instantly share code, notes, and snippets.

@leemour
Forked from marcamillion/console.rb
Last active August 29, 2015 14:02
Show Gist options
  • Save leemour/ea15148bc95ea31f3a1a to your computer and use it in GitHub Desktop.
Save leemour/ea15148bc95ea31f3a1a to your computer and use it in GitHub Desktop.
Rails 4 cache_counter for has_and_belongs_to_many relationship
## 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
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
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
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