Forum: Ruby on Rails counter_cache for has_many through associations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7bf3e233fdb80476d8de8730d0bf2c55?d=identicon&s=25 Amit (Guest)
on 2015-01-10 20:35
(Received via mailing list)
class User < ActiveRecord::Base
  has_many :likes
  has_many :liked_things, :through => :likes
end

class Thing < ActiveRecord::Base
  has_many :likes
  has_many :liked_by_users, :through => :likes
end

class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :shot
end

This is my setup, and I have a `likes_count` column on Things Table. Is
there any way to keep that count updating using counter_cache ? I got it
working counter_cache on has_many association but failing to do same
with
has_many through association.
2cc9feaac138b891ae74e9fa559b34dc?d=identicon&s=25 John Sanderbeck (jsanderbeck)
on 2016-01-07 15:31
I am struggling with this as well.

What appears to be happening is that the deletes from the join table do
not fire the counter_cache update.

From what I have read, delete's do not fire events and that is the way
it is designed in Rails 4.

I have tried multiple workarounds from doing an after_save event,
putting the join table in it's own model, etc...  Nothing I have done
seems to decrement the count.

Anxious to see if any Ruby experts see this post and let us know the
best way to fix this.

John
This topic is locked and can not be replied to.