Question

In my Rails app, I have a model called Steps that can have many images:

class Step < ActiveRecord::Base
     has_many :images, :dependent => :destroy
     ...

Because of the dependent destroy condition, when I delete a step, it deletes all corresponding images.

However, I'd like the deletion of images to happen in a background task. I know I can do that using sidekiq by calling a worker in the controller with something like this:

    @step.images.each do |image|
      CarrierwaveImageDeleteWorker.perform_async(image.id)
    end

But since the images are automatically deleted because of the dependent destroy condition, I'm not sure how I can call the sidekiq worker. What would be the best way to have images automatically call a sidekiq background task once the destroy action is triggered?

Was it helpful?

Solution

I fixed this issue by overriding the default destroy method in my Image model as follows:

  # override destroy method to put it in a background task
  class Image < ActiveRecord::Base

  def destroy
    CarrierwaveImageDeleteWorker.perform_async(self.id)
  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top