0
我有以下的模型如下關係:刪除記錄時,計數器緩存達到0
+------+ 1 n +------------+ n 1 +-----+
| Post |--------| TagMapping |--------| Tag |
+------+ +------------+ +-----+
現在,在我的應用程序Tag
的Post
計數讀得很頻繁,只有當一個新的職位是改變補充說,這與閱讀相比很少發生。因此,我決定將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,我該如何刪除記錄?