【问题标题】:Counter cache for scopes范围的计数器缓存
【发布时间】:2014-07-08 22:27:53
【问题描述】:

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

我正在做很多类似的查询

user.collections.got.count

where got 是我的集合模型中的一个范围

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 counter-cache


    【解决方案1】:

    您可以将 after_save 回调添加到 Collection 类并自己进行计数器缓存操作。

    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
    

    【讨论】:

    • 每次只做一个新的计数而不是增加它会更容易和更准确吗?
    • 是条件中的“或”用于说明目的吗?如果是直接代码,我认为可能是错误的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 2015-10-27
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多