我posts_count
在模型中添加了一个列Tag
:
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
现在我正在尝试根据这个问题为他们构建一个计数器缓存(为多对多关联创建一个计数器缓存):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
但是当我创建一个时我得到了这个Post
:
undefined method `tag' for []:ActiveRecord::Relation
我认为这部分有问题:self.taggings.tag.id
但我不太确定如何修复它。
有什么建议么?
楷模:
**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
编辑
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
标记.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