I added a posts_count
column to the Tag
model:
create_table "tags", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "posts_count", :default => 0, :null => false
end
Now I'm trying to build a counter cache for them based on this question (creating a counter cache for a many-to-many association): Counter cache for a model with a many-to-many association
post.rb:
private
after_create :increment_tag_counter_cache
after_destroy :decrement_tag_counter_cache
def increment_tag_counter_cache
Tag.increment_counter(:posts_count, self.taggings.tag.id)
end
def decrement_tag_counter_cache
Tag.decrement_counter(:posts_count, self.taggings.tag.id)
end
But I'm getting this when I create a Post
:
undefined method `tag' for []:ActiveRecord::Relation
I think there is something wrong with this part: self.taggings.tag.id
But I'm not very sure how to fix it.
Any suggestions?
Models:
**post.rb:**
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
**tag.rb:**
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
**tagging:**
attr_accessible :tag_id, :post_id
belongs_to :post
belongs_to :tag
EDIT
post.rb:
before_save :publish_post
protected
def publish_post
if self.status == "Published" && self.published_at.nil?
self.published_at = Time.now
end
end
tagging.rb:
private
def increment_tag_counter_cache
if self.post.status == "Published" && self.post.published_at.nil?
Tag.increment_counter(:posts_count, self.tag.id)
end
end