Caching 在“更新后”回调中使用减量计数器是减去2?
我有三种型号。雇主、用户、工作Caching 在“更新后”回调中使用减量计数器是减去2?,caching,ruby-on-rails-4,increment,counter-cache,Caching,Ruby On Rails 4,Increment,Counter Cache,我有三种型号。雇主、用户、工作 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”的布尔列。雇主用户计数是通过计算标记为“当前”的所有相关作业而得出的 我选择
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过滤器来增加或减少雇主模型中的用户数。增量按预期工作,但无论我如何调整代码……减量将计数的值降低2
我相信我可以清理这些方法一点…可能有一些冗余
1为什么减量减去2而不是1?
2活动记录缓存计数器能否处理这样的逻辑?
gem“counter_culture”很好地处理了这一点……并清理了我的代码
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