Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enqueue ActiveJob task with destroyed object

In controller's action, I destroy a record and then pass it as an argument to ActiveJob.

def destroy
  post = Post.find params[:id]
  post.destroy
  CleanUpJob.perform_later post
end

And in my job's perform, I need to do some cleanup actions with that destroyed record.

def perform(post)
  log_destroyed_content post.id, post.title
end

When I call it as delayed with .perform_later - it does not execute at all. But when I change to .perform_now - it works as expected. This Job needs to deal with both destroyed and persisted records.

I'm using lates Rails, development env with default async activejob adapter.

like image 589
Molfar Avatar asked Oct 19 '25 05:10

Molfar


2 Answers

When you call .perform_later with an ActiveRecord object, ActiveJob will try to serialize it into a global id

You are deleting your record from the database, which means your job won't find it when it runs.

You could pass a hash with all the attributes: CleanUpJob.perform_later(post.attributes)

Alternatively, you could flag your model for deletion and call destroy in the job when you are actually done with the record. Think of it as soft-deleting the record first:

# in the controller
def destroy
  post = Post.find params[:id]
  post.update(state: :archived) # or whatever makes more sense for your application
  CleanUpJob.perform_later(post.id, post.title)
end

# in the job
def perform(post_id, post_title)
  log_destroyed_content(post_id, post_title)
  post.destroy
end

You will want to make sure to exclude 'soft-deleted' records from your user-facing queries.

like image 142
Fito von Zastrow Avatar answered Oct 21 '25 06:10

Fito von Zastrow


Instead of passing the destroyed post just pass its id and title.

# in the controller
def destroy
  post = Post.find params[:id]
  post.destroy
  CleanUpJob.perform_later(post.id, post.title)
end

# in the job
def perform(post_id, post_title)
  log_destroyed_content(post_id, post_title)
end
like image 34
spickermann Avatar answered Oct 21 '25 06:10

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!