具有多对多关联的模型的计数器缓存

我有一个具有many-to-many关联的PostTag模型:

post.rb:

 class Post  :destroy has_many :tags, :through => :taggings attr_writer :tag_names after_save :assign_tags def tag_names @tag_names || tags.map(&:name).join(" ") end private def assign_tags ntags = [] @tag_names.to_s.split(" ").each do |name| ntags << Tag.find_or_create_by_name(name) end self.tags = ntags end end 

tag.rb:

 class Tag  :destroy has_many :posts, :through => :taggings has_many :subscriptions has_many :subscribed_users, :source => :user, :through => :subscriptions end 

tagging.rb(连接表的模型):

 class Tagging < ActiveRecord::Base belongs_to :post belongs_to :tag end 

我想创建一个:counter_cache来跟踪标签有多少post。

如何在这种多对多关联中实现这一目标?

编辑:

我以前这样做过:

comment.rb:

 belongs_to :post, :counter_cache => true 

但现在post.rb文件中没有belongs_to 。 我有点困惑。

似乎没有真正简单的方法来做到这一点。 如果你看看上一篇文章。 看起来这种情况经常发生,而且很遗憾,rails没有简单的方法来完成这项任务。 你需要做的是写一些像这样的代码。

虽然,我也建议调查has_and_belongs_to_many关系,因为这可能就是你在这里所拥有的。

A(Tag)有很多C(post)到B(标记)

 class C < ActiveRecord::Base belongs_to :B after_create :increment_A_counter_cache after_destroy :decrement_A_counter_cache private def increment_A_counter_cache A.increment_counter( 'c_count', self.BAid ) end def decrement_A_counter_cache A.decrement_counter( 'c_count', self.BAid ) end end 

tagging.rb(连接表的模型):

 class Tagging < ActiveRecord::Base belongs_to :post, counter_cache: :tags_count belongs_to :tag, counter_cache: :posts_count end 

在列中添加列迁移posts_count整数在post中添加列迁移tags_count整数