4

I've set up some counter_caches in my app before but only for simple belongs_to relationships.

I'm doing a lot of queries like

user.collections.got.count

where got is a scope in my collection model

belongs_to :user
scope :got, -> { where(status: 'Got') }

Can I set up a counter_cache to count the number of user.collections that are marked as "got"? The problem I see is that counter_cache only updates with create or destroy but not update actions. Is there a good method for this?

Ossie
  • 1,103
  • 2
  • 13
  • 31

1 Answers1

2

you can add a after_save callback to the Collection class and do the counter cache manipulation by yourself.

class Collection < ActiveRecord::Base
  belongs_to :user

  after_save :update_got_counter

  def update_got_counter
    if changed_attributes.has_key?('status')
      # do the cache manipulation here
      User.increment_counter(:collections_get_count, user.id)
      or
      User.decrement_counter(:collections_get_count, user.id)
    end
  end
end
nickcen
  • 1,682
  • 10
  • 10
  • Would it be easier and more accurate to just do a new count each time rather than increment it? – Ossie Jul 08 '14 at 14:31
  • is the "or" in the conditional for illustration purposes? If it were direct code, I think it might be wrong. – kronn Sep 06 '16 at 11:55