Note that there are some explanatory texts on larger screens.

plurals
  1. POcounter_cache not decrementing for has_many associations in ActiveReord
    text
    copied!<p>My Rails 3 app has 2 models and a third that's join table between them and their has_many relationships. Basically, User and Show are joined by SavedShow, allowing users to save a list of shows:</p> <pre><code>class Show &lt; ActiveRecord::Base has_many :saved_shows has_many :users, :through =&gt; :saved_shows end class User &lt; ActiveRecord::Base has_many :saved_shows has_many :shows, :through =&gt; :saved_shows end class SavedShow &lt; ActiveRecord::Base belongs_to :user, :counter_cache =&gt; :saved_shows_count belongs_to :show end </code></pre> <p>I've noticed that the counter_cache field (shows_saved_count) gets incremented automatically just fine, but not decremented. The core of the issue seems to be that removing shows from a user's list is done via delete, which does not trigger updating of the counter_cache:</p> <pre><code>current_user.shows.delete(@show) </code></pre> <p>However, I can't call the destroy method here, since that not only deleted the User/Show association in SavedShow, but also the Show object itself, which is not what I want.</p> <p>Is a counter_cache in this kind of scenario not an appropriate use?</p> <p>There appears to be a <a href="https://rails.lighthouseapp.com/projects/8994/tickets/1196-counter_cache-not-decrementing-on-delete" rel="nofollow">discussion</a> about this as a bug back in 2009, and fixes were discussed, but I'm still seeing the issue in the latest Rails 3.0.</p> <p>I would just write my own custom handling in the model, but there seems to be no after_delete callback that I can hook into (presumably this is the reason decrementing doesn't work in the first place). Right now, there's only one place in my own code where a delete of the association could occur, so I'll just manually make a call to update the counter, but this seems like like such a fundamental shortcoming or bug of ActiceRecord associations with counter_cache, that I'm wondering if I'm not just missing something.</p> <p>If this is indeed a genuine problem with counter_caches, what would be the best workaround?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload