我有以下具有以下关系的模型:
+------+ 1 n +------------+ n 1 +-----+
| Post |--------| TagMapping |--------| Tag |
+------+ +------------+ +-----+
现在,在我的应用程序中Post
,a 的计数Tag
被非常频繁地读取,并且仅在添加新帖子时才会更改,与读取相比,这种情况很少发生。因此,我决定为模型添加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
标签映射.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
标签.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 ,如何删除记录?