Rails:如何使用self-refere实现计数器缓存通过has_many实现多对多:通过

如何使用has_many :through的自引用多对多关系来滚动自己的计数器缓存?

我需要跟踪每篇文章的引用次数和参考数量

我大致使用了这个问题答案中的代码:

 class Publication  :citations, :source => :reference has_many :references, :foreign_key => "reference_id", :class_name => "Citation" has_many :refered_publications, :through => :references, :source => :publication end class Citation  "Publication" end 

Rails计数器缓存机制在内部使用increment_counter和decrement_counter方法。 您应该只能从标准的ActiveRecord回调中调用这些方法。

像这样的东西应该给你的想法:

 class Citation < ActiveRecord::Base belongs_to :publication belongs_to :reference, :class_name => "Publication" after_create :increment_counter_cache after_destroy :decrement_counter_cache private def decrement_counter_cache Publication.decrement_counter("citations_counter", publication_id) end def increment_counter_cache Publication.increment_counter("citations_counter", publication_id) end 

结束

对于has_many:通过AssociationAutomatic,删除连接模型是直接的,不会触发销毁回调。 因此,减少计数器在这种情况下不起作用