4

我之前在我的应用程序中设置了一些 counter_caches,但仅用于简单的 belongs_to 关系。

我正在做很多查询,例如

user.collections.got.count

我的集合模型中的范围在哪里

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

我可以设置一个 counter_cache 来计算标记为“got”的 user.collections 的数量吗?我看到的问题是 counter_cache 仅使用创建或销毁而不是更新操作进行更新。有什么好的方法吗?

4

1 回答 1

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
于 2014-07-08T14:27:53.577 回答