使ActiveJob任务与已破坏的对象排队

时间:2019-03-30 20:47:49

标签: ruby-on-rails ruby rails-activejob

在控制器的操作中,我销毁一条记录,然后将其作为参数传递给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时,它可以按预期工作。这项工作需要处理被破坏和持久的记录。

我使用的是Lates Rails,带有默认异步activejob适配器的开发环境。

2 个答案:

答案 0 :(得分:2)

当您使用.perform_later对象调用ActiveRecord时,ActiveJob将尝试将其序列化为global 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

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

答案 1 :(得分:1)

与其传递被破坏的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