ruby-on-railsrubyactivemodelcounter-cache

How trigger counter cache after destroy_all


I have to destroy a big list of data, and update my counter cache, but when I user destroy_all counter cache is called at every delete. Is there any way to update my counter only after the destroy_all?

I already tried ActiveModel Callbacks, but they are the same as destroy_all, called one time for each record.

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

Solution

  • You can use 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
    

    If you depend on callbacks that must be triggered this might not be an option.