Rails: How to implement counter caching with self-referential Many to Many via has_many :through

ε祈祈猫儿з 提交于 2019-12-09 18:42:25

问题


How can I roll my own counter cache for a self-referential many-to-many relationship that uses has_many :through?

I need to track the number of citations and references for each article

I'm using roughly the code from the answer to this question:

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

class Citation < ActiveRecord::Base
  belongs_to :publication
  belongs_to :reference, :class_name => "Publication"
end

回答1:


The Rails counter cache mechanism uses the increment_counter and decrement_counter methods internally. You should just be able to invoke those methods from the standard ActiveRecord callbacks.

Something like this should give you the idea:

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

end




回答2:


For has_many :through AssociationAutomatic, deletion of join models is direct, no destroy callbacks are triggered. So decrement counter will not work in this case



来源:https://stackoverflow.com/questions/978779/rails-how-to-implement-counter-caching-with-self-referential-many-to-many-via-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!