0

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
Eduardo
  • 37
  • 1
  • 9
  • `destroy_all` invokes all callbacks (including updating counter cache columns), `delete_all` does not trigger any callback, you have to update the value of the counter cache column manually at the end though – arieljuod Aug 28 '19 at 15:38

1 Answers1

0

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.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52