我有三个型号。雇主、用户、工作。
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活动记录缓存计数器可以处理这样的逻辑吗?
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发布于 2013-09-19 02:19:38
gem "counter_culture“处理了这一点,nicely...and清理了我的代码。
https://stackoverflow.com/questions/18878396
复制相似问题