You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Rails与Sidekiq执行Active Job时遇NotImplementedError求助

问题排查与解决方案

核心错误:任务类方法名错误

Active Job要求任务类必须实现perform方法作为任务执行入口,你错误地在ExpireRifJob里定义了perform_later方法——这是调用任务的方法,并非任务内部的执行方法,这直接触发了NotImplementedError(Rails找不到规定的perform方法)。

次要错误:控制器变量拼写错误

在create方法中,你调用任务时使用了@rif.id,但实际创建的实例是@rifa,变量名拼写错误会导致nil.id的潜在问题。

额外优化点:日期类型适配

expireDate是date类型,而wait_until需要接收DateTime对象。直接传入Date会默认转为当天00:00:00,若需要在当天特定时间执行(比如当日结束时),可以显式转换,避免执行时间不符合预期。


修复后的代码

1. 修正后的Active Job类

class ExpireRifJob < ApplicationJob
  queue_as :default

  # 必须实现perform方法作为执行入口
  def perform(rif_id)
    Rifa.find(rif_id).update(is_expired: true)
  end
end

2. 修正后的控制器create方法

def create
  @rifa = Rifa.new(rif_params)
  if @rifa.save
    render json: @rifa, status: :created
    # 修正变量名,同时将Date转为DateTime(可选,根据需求调整执行时间)
    execute_at = @rifa.expireDate.end_of_day # 当天23:59:59执行,也可使用beginning_of_day
    ExpireRifJob.set(wait_until: execute_at).perform_later(@rifa.id)
  else
    render json: { errors: @rifa.errors.full_messages },
           status: :unprocessable_entity
  end
end

验证步骤

  1. 重启Sidekiq服务,确保代码更新生效
  2. 创建新的Rifa记录,检查Sidekiq队列是否正确接收任务
  3. 到达指定执行时间后,确认任务执行成功,Rifa的is_expired字段已设为true

内容的提问来源于stack exchange,提问作者Javier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:15:29