ruby-on-railscallbackcounter-cacheafter-save

How can I invoke the after_save callback when using 'counter_cache'?


I have a model that has counter_cache enabled for an association:

class Post
  belongs_to :author, :counter_cache => true
end

class Author
  has_many :posts
end

I am also using a cache fragment for each 'author' and I want to expire that cache whenever @author.posts_count is updated since that value is showing in the UI. The problem is that the internals of counter_cache (increment_counter and decrement_counter) don't appear to invoke the callbacks on Author, so there's no way for me to know when it happens except to expire the cache from within a Post observer (or cache sweeper) which just doesn't seem as clean.

Any ideas?


Solution

  • I ended up keeping the cache_counter as it was, but then forcing the cache expiry through the Post's after_create callback, like this:

    class Post
      belongs_to :author, :counter_cache => true
      after_create :force_author_cache_expiry
    
      def force_author_cache_expiry
        author.force_cache_expiry!
      end
    end
    
    class Author
      has_many :posts
    
      def force_cache_expiry!
        notify :force_expire_cache
      end
    end
    

    then force_expire_cache(author) is a method in my AuthorSweeper class that expires the cache fragment.