ruby-on-rails – Rails:如何通过自引用实现计数器缓存多对多通过has_many:通过

ruby-on-rails – Rails:如何通过自引用实现计数器缓存多对多通过has_many:通过,第1张

概述如何使用has_many:through来自我引用多对多关系? 我需要跟踪每篇文章的引用次数和参考数量 我大致使用了这个question的答案中的代码: class Publication < ActiveRecord::Base has_many :citations has_many :cited_publications, :through => :citations, :sourc 如何使用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 => :publicationendclass 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

结束

总结

以上是内存溢出为你收集整理的ruby-on-rails – Rails:如何通过自引用实现计数器缓存多对多通过has_many:通过全部内容,希望文章能够帮你解决ruby-on-rails – Rails:如何通过自引用实现计数器缓存多对多通过has_many:通过所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1291536.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存