ruby-on-rails – Rails:如何通过自引用实现计数器缓存多对多通
发布时间:2020-12-17 03:08:24 所属栏目:百科 来源:网络整理
导读:如何使用has_many:through来自我引用多对多关系? 我需要跟踪每篇文章的引用次数和参考数量 我大致使用了这个question的答案中的代码: class Publication ActiveRecord::Base has_many :citations has_many :cited_publications,:through = :citations,:so
如何使用has_many:through来自我引用多对多关系?
我需要跟踪每篇文章的引用次数和参考数量 我大致使用了这个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 解决方法
Rails计数器缓存机制在内部使用
increment_counter和
decrement_counter方法.您应该能够从
standard ActiveRecord callbacks调用这些方法.
这样的事情会给你一个想法: 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 结束 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |