首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在after_update回调中使用decrement_counter等于减去2?

在after_update回调中使用decrement_counter等于减去2?
EN

Stack Overflow用户
提问于 2013-09-19 01:15:20
回答 1查看 193关注 0票数 0

我有三个型号。雇主、用户、工作。

代码语言:javascript
复制
 class Employers
    has_many :jobs
    has_many :users, through: :jobs
 end

 class User
    has_many :jobs
 end

 class Job
    belongs_to :user
    belongs_to :employer
 end

作业模型有一个名为"current“的布尔列。雇主用户计数是通过对标记为“当前”的所有相关工作进行计数而得出的。

我选择使用自己的缓存计数器,而不是使用活动记录。

我正在使用作业模型中的before筛选器来增加或减少雇主模型中的users_count。递增按预期工作,但无论我如何调整,code...the递减都会将计数值减少2。

我确信我可以清理掉这些方法,bit...there可能会有一些冗余。

为什么减量是减去2而不是1?

2活动记录缓存计数器可以处理这样的逻辑吗?

代码语言:javascript
复制
class Job

    before_destroy :change_employer_users_counter_cache_after_destroy
    before_create :change_employer_users_counter_cache_after_create
    before_update :change_employer_users_counter_cache_after_update


    def change_employer_users_counter_cache_after_create
       Operator.increment_counter(:users_count, self.operator_id) if self.current == true
    end

    def change_employer_users_counter_cache_after_update
       if self.current_changed?
          if self.current == true
            Operator.increment_counter(:users_count, self.operator_id)
          else
            Operator.decrement_counter(:users_count, self.operator_id)
          end
       end
    end  

    def change_employer_users_counter_cache_after_destroy
       Operator.decrement_counter(:users_count, self.operator_id)
    end

end
EN

回答 1

Stack Overflow用户

发布于 2013-09-19 02:19:38

gem "counter_culture“处理了这一点,nicely...and清理了我的代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18878396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档