使用已删除的对象排队ActiveJob任务

4
在控制器的操作中,我会销毁一条记录,然后将其作为参数传递给ActiveJob。
def destroy
  post = Post.find params[:id]
  post.destroy
  CleanUpJob.perform_later post
end

在我的工作中,我需要对被删除的记录进行一些清理操作。

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

当我使用.perform_later调用它时,它根本不执行。但是当我改为使用.perform_now时,它按预期工作。这个任务需要处理已经销毁和持久化的记录。

我正在使用最新版本的Rails,在开发环境下使用默认的异步activejob适配器。

2个回答

5
当你使用.perform_later方法并传入一个ActiveRecord对象时,ActiveJob会尝试将其序列化成一个全局 id
你正在从数据库中删除记录,这意味着当任务运行时它找不到该记录。
你可以传递一个包含所有属性的哈希值:CleanUpJob.perform_later(post.attributes)
或者,你可以标记你的模型以删除,并在你实际完成记录时在作业中调用destroy。把它想象成先软删除记录:
# 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

您需要确保从用户界面的查询中排除“软删除”记录。


2

不要将已删除的post直接传递,只需传递其idtitle

# 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接