Search code examples
ruby-on-rails-4rails-activejobdependent-destroy

Handle dependent destroy via active jobs


I have a couple models with many children. Dependent destroy has gotten really heavy. Anyone know of a way to tie dependent destroy into active jobs? Or, is my only option to remove dependent destroy and role my own jobs via callbacks on the parent model?


Solution

  • You can create a worker to destroy the models async and enqueue it's deletion. Something like:

    class ComplexModelDeletion < ActiveJob::Base
      def perform(model)
        model.destroy!
      end
    end
    

    And the model could be something like:

    class Model < ActiveRecord::Base
      def destroy_later
        ComplexModelDeletion.enqueue(self)
      end
    end
    

    Then, whenever you need to kill an instance of this model, you could call Model#destroy_later to enqueue it. You could even mark the object as deleted before enqueuing it just to prevent it from being retrieve from DB before it is actually killed.

    Not sure if this would work as is, but just to give you an idea of what you could do.