销毁时rails计数器缓存



例如,我有三个模型用户,问题和答案,它们之间的关系是:

class User < ActiveRecord::Base
  has_many :answers
  has_many :questions
end
class Question < ActiveRecord::Base
  has_many :answers, :dependent => :destroy
  belongs_to :user, :counter_cache => true
end
class Answer < ActiveRecord::Base
  belongs_to :user, :counter_cache => true
  belongs_to :question, :counter_cache => true
end

然后,当我想销毁一个问题(有1000个答案)时,会发生以下情况:答案将逐一销毁,并更新用户模型中的计数器,甚至是我想销毁的问题中的计数器。这将需要很长时间才能进行计数器更新。

我的问题是如何让它更快?

我有自己的解决方案,如下所示:

步骤1:删除依赖的destroy,它将在销毁自身之前调用计数器更新。

步骤2:添加我自己的before_edestroy,就像这个

before_destroy :delete_dependents

使用delete_all函数进行删除,而不调用任何before_edestroy,然后调用reset_counters函数重置User模型中的计数器。

类问题的完整代码:

class Question < ActiveRecord::Base
  has_many :answers
  has_many :answer_users, :through => :answers, :source => :user, :uniq => true
  belongs_to :user, :counter_cache => true
  before_destroy :delete_dependents
  private
  def delete_dependents
    answer_user_ids = self.answer_user_ids # eager loading for store the answer users id
    Answer.delete_all(:question_id => self.id)
    answer_user_ids.each do |u_id|
      User.reset_counters u_id, :answers
    end
  end
end

PS:如果有太多的计数器需要重置,你可能需要一个后台工作来解决。

最新更新