Using acts_as_paranoid with DelayedJob?

199 Views Asked by At

Can someone tell me precisely how to integrate acts_as_paranoid with DelayedJob? I've tried creating a class Delayed::Backend::ActiveRecord::Job and adding acts_as_paranoid to it but even if I use an initializer and require the new class, acts_as_paranoid doesn't seem to do anything.

I'm not getting any errors so paranoia seems to be installed correctly and the job is cleanly deleted when it completes successfully - which is of course what I'm trying to prevent.

Happy to try any debugging suggestions if nobody reads this and immediately knows how I've screwed up.

2

There are 2 best solutions below

0
On

I know you answered your own question, sort of, but your answer doesn't help people landing here looking to actually integrate DelayedJob with acts_as_paranoid so I thought I'd explain this for others.

  1. Create migration to add deleted_at to delayed_jobs:

    rails generate migration add_deleted_at_to_delayed_jobs deleted_at:datetime
    
  2. Run migrations:

    rake db:migrate
    
  3. Extend the Delayed::Job class to add acts_as_paranoid:

    config/initializers/delayed_job.rb

    class Delayed::Job
    
      acts_as_paranoid
    
    end
    

That's it!

Now when a job gets completed, you'll see that it doesn't get removed from the delayed_jobs table, it just gets a timestamp put in the deleted_at column so that the workers don't pick it up.

ProTip: The deleted_at column indicates when the job was completed as well.

0
On

Turns out I fell for the 'default scope' problem. acts_as_paranoid changes the default scope so that a find only returns entries that have not been soft-deleted. If you want to see ALL entries, including the soft-deleted one, you need to either add with_deleted as a scope for your query or, when adding acts_as_paranoid to your class, add as per the example:

class Client < ActiveRecord::Base
  acts_as_paranoid without_default_scope: true

  ...
end

With either of these changes, things are working.