扶手:如何通过的has_many实施反缓存与自我指涉的多对多:通过 [英] Rails: How to implement counter caching with self-referential Many to Many via has_many :through
问题描述
我如何能推出自己的反缓存使用一种自我指涉的许多一对多的关系,的has_many:通过
我需要跟踪引文和参考文献的数量每篇文章
我使用的大致code,从这个问题的答案<一个href="http://stackoverflow.com/questions/536261/tricky-active-record-relationships-polymorphic-bi-directional-self-referential">question:
类出版物&LT;的ActiveRecord :: Base的
的has_many:引用
的has_many:cited_publications,:通过=&GT; :引用,:源=&GT; :参考
的has_many:引用:foreign_key =&GT; reference_id:将class_name =&GT; 引文
的has_many:refered_publications,:通过=&GT; :引用:源=&GT; :发布
结束
类引用&LT;的ActiveRecord :: Base的
belongs_to的:出版
belongs_to的:参考:将class_name =&GT; 发布
结束
Rails的计数器缓存机制使用的 increment_counter 和 decrement_counter 的内部方法。你应该能够调用从标准的ActiveRecord的回调,这些方法。
像这样的东西应该给你的想法:
类引用&LT;的ActiveRecord :: Base的
belongs_to的:出版
belongs_to的:参考:将class_name =&GT; 发布
after_create:increment_counter_cache
after_destroy:decrement_counter_cache
私人
高清decrement_counter_cache
Publication.decrement_counter(citations_counter,publication_id)
结束
高清increment_counter_cache
Publication.increment_counter(citations_counter,publication_id)
结束
结束
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
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
这篇关于扶手:如何通过的has_many实施反缓存与自我指涉的多对多:通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!