title: Rails: How to implement counter caching with self-referential Many to Many via has_many :through
body: <p>How can I roll my own counter cache for a self-referential many-to-many relationship that uses <code>has_many :through</code>?</p>
  
  <p>I need to track the number of citations and references for each article</p>
  
  <p>I'm using roughly the code from the answer to this <a href="https://stackoverflow.com/questions/536261/tricky-active-record-relationships-polymorphic-bi-directional-self-referential">question</a>:</p>
  
  <pre><code>class Publication &lt; ActiveRecord::Base
    has_many :citations
    has_many :cited_publications, :through =&gt; :citations, :source =&gt; :reference
    has_many :references, :foreign_key =&gt; "reference_id", :class_name =&gt; "Citation"
    has_many :refered_publications, :through =&gt; :references, :source =&gt; :publication
  end
  
  class Citation &lt; ActiveRecord::Base
    belongs_to :publication
    belongs_to :reference, :class_name =&gt; "Publication"
  end
  </code></pre>