I have the following model with the following relations:
+------+ 1 n +------------+ n 1 +-----+
| Post |--------| TagMapping |--------| Tag |
+------+ +------------+ +-----+
Now, in my application the Post
count of a Tag
is read very frequently and only changed when a new post is added, which compared to reading happens very rarely. Because of this I decided to add posts_count
attribute to the Tag
Model.
Here are my ActiveRecord models:
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
When I destroy all the posts of a tag the posts_count
reduces to correctly to 0. But the Tag
record still exists. How can I delete the record if posts_count
reached 0?