gpt4 book ai didi

ruby-on-rails - rails : How to implement counter caching with self-referential Many to Many via has_many :through

转载 作者:行者123 更新时间:2023-12-03 15:58:47 24 4
gpt4 key购买 nike

如何为使用 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_counterdecrement_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 : How to implement counter caching with self-referential Many to Many via has_many :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/978779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com