2013-04-11 16 views
0

我有以下的模型如下關係:刪除記錄時,計數器緩存達到0

+------+ 1 n +------------+ n 1 +-----+ 
| Post |--------| TagMapping |--------| Tag | 
+------+  +------------+  +-----+ 

現在,在我的應用程序TagPost計數讀得很頻繁,只有當一個新的職位是改變補充說,這與閱讀相比很少發生。因此,我決定將posts_count屬性添加到Tag型號。

這裏是我的ActiveRecord模型:

Post.rb:

class Post < ActiveRecord::Base 

    # other stuff ... 

    # relations 
    has_many :tag_mappings, dependent: :destroy 
    has_many :tags, through: :tag_mappings 

    # assign a new set of tags 
    def tags=(new_tags) 
    # generate a list of tag objects out of a listing 
    if new_tags && !new_tags.instance_of?(Array) 
     new_tags = new_tags.split(/\s+/).map do |tag| 
     tag = Tag.find_or_initialize_by_name tag 
     tag.save ? tag : false 
     end.select {|v| v } 
    end 

    # remove the spare tags which aren't used by any posts 
    ((tags || []) - new_tags).each do |tag| 
     tag.destroy if tag.posts.count <= 1 
    end 

    # replace the old tags with the new ones 
    tags.delete_all 
    new_tags.each do |tag| 
     # prevent tagging the post twice with the same tag 
     tags << tag unless TagMapping.exists? post_id: self[:id], tag_id: tag.id 
    end 
    end 
end 

TagMapping.rb:

class TagMapping < ActiveRecord::Base 

    # other stuff ... 

    # create a cache for the post count in the Tag model 
    belongs_to :tag, counter_cache: :posts_count 
    belongs_to :post 
end 

Tag.rb:

class Tag < ActiveRecord::Base 

    # other stuff ... 

    has_many :tag_mappings, dependent: :destroy 
    has_many :posts, through: :tag_mappings 
end 

當我摧毀標籤的所有帖子posts_count正確地降低到0.但Tag記錄仍然存在。如果posts_count達到0,我該如何刪除記錄?

回答

0

而不是使用計數器緩存我只是用了after_destroyafter_create鉤來跟蹤後計數:

class TagMapping < ActiveRecord::Base 

    # other stuff 

    after_create :increment_post_count 
    after_destroy :decrement_post_count 

    def increment_post_count 
    tag.posts_count += 1 
    tag.save 
    end 

    def decrement_post_count 
    tag.posts_count -= 1 
    tag.save 
    tag.destroy if tag.posts_count <= 0 
    end 
end