Counter_cache is not reduced for has_many associations in ActiveReord

My Rails 3 has two models, and the third is a table of connections between them and their has_many relationships. Basically, the user and the show are combined by SavedShow, which allows users to save the list of shows:

class Show < ActiveRecord::Base
  has_many :saved_shows
  has_many :users, :through => :saved_shows
end

class User < ActiveRecord::Base
  has_many :saved_shows
  has_many :shows, :through => :saved_shows
end

class SavedShow < ActiveRecord::Base
  belongs_to :user, :counter_cache => :saved_shows_count
  belongs_to :show
end

I noticed that the counter_cache (show_saved_count) field automatically increases automatically, but does not decrease. The essence of the problem is that the removal of the show from the list of users is performed using delete, which does not cause the counter_cache update:

current_user.shows.delete(@show)

However, I cannot call the destroy method here, since it not only removed the User / Show association in SavedShow, but the Show object itself, which is not what I want.

Is counter_cache unsuitable in such a scenario?

, 2009 , , Rails 3.0.

, , , after_delete, (-, , ). , , , ActiceRecord counter_cache, , -.

counter_caches, ?

+3
1

, Rails 2.3. , , :

belongs_to :user, :counter_cache => :saved_shows_count, :touch => true

update_at association.delete(object).

, , .

: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2824-patch-has_many-through-doesnt-update-counter_cache-on-join-model-correctly#ticket-2824-18

+1

Source: https://habr.com/ru/post/1768922/


All Articles