Rails: how to implement counter caching using the self-referencing function Many to Many through has_many: through

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

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

I am 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 
+4
source share
2 answers

The Rails counter caching mechanism uses increment_counter and decment_counter internally. You should simply use these methods from standard ActiveRecord callbacks .

Something like this should give you an 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

+4
source

For has_many: through AssociationAutomatic, removing the merge moments directly, no destroy callbacks are triggered. Thus, the decrement counter will not work in this case

+3
source

Source: https://habr.com/ru/post/1286043/


All Articles