destroy_all 后如何触发计数器缓存

How trigger counter cache after destroy_all

我必须销毁一大堆数据,并更新我的计数器缓存,但是当我使用 destroy_all 时,每次删除都会调用计数器缓存。有什么方法可以仅在 destroy_all 之后更新我的计数器?

我已经尝试过 ActiveModel 回调,但它们与 destroy_all 相同,每条记录调用一次。

  belongs_to :research, counter_cache: :total_participants
  ResearchParticipant.from_research(@research_id).destroy_all

您可以使用 delete_all which doesn't instantiate objects. Meaning callbacks aren't called. Then reset the cache with reset_counters.

ResearchParticipant.from_research(@research_id).delete_all
Research.reset_counters(@research_id, :research_participants)
# assuming Research has_many :research_participants, counter_cache: :total_participants

如果您依赖必须触发的回调,这可能不是一个选项。