Ruby on rails Rails:如何通过自引用多对多via实现计数器缓存

Ruby on rails Rails:如何通过自引用多对多via实现计数器缓存,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,如何为使用has_many:through的自引用多对多关系滚动自己的计数器缓存 我需要跟踪每篇文章的引用和参考文献数量 我使用的代码大致如下: 类发布:被引用,:来源=>:参考 有很多:引用,:外键=>“引用id”,:类名=>“引用” 有许多:引用的出版物,:至=>:references,:source=>:publication 结束 类引用“发布” 结束 Rails计数器缓存机制在内部使用和方法。您应该能够从中调用这些方法 像这样的东西应该会让你产生这样的想法: class Citatio

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

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

我使用的代码大致如下:

类发布:被引用,:来源=>:参考 有很多:引用,:外键=>“引用id”,:类名=>“引用” 有许多:引用的出版物,:至=>:references,:source=>:publication 结束 类引用“发布” 结束
Rails计数器缓存机制在内部使用和方法。您应该能够从中调用这些方法

像这样的东西应该会让你产生这样的想法:

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
类引用“发布”
创建后:递增计数器缓存
销毁后:递减计数器缓存
私有的
def减量计数器缓存
出版物.减量计数器(“引用计数器”,出版物id)
结束
def增量计数器缓存
出版物.增量计数器(“引用计数器”,出版物id)
结束

end

对于has\u many:通过AssociationAutomatic,直接删除连接模型,不会触发销毁回调。所以减量计数器在这种情况下不起作用

谢谢John。这大概是我需要知道的1/2,但它让我走了。实际上,我不得不增加和减少出版物id文章的数量和参考id文章的数量。很好,我很高兴这有帮助。我想你必须增加这两个。
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