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

Rails中Ajax更新记录后重定向保留PATCH方法引发路由错误

问题原因分析

你发起的是Ajax PATCH请求,当控制器返回302重定向时,Ajax会默认保留原请求方法(PATCH)去访问重定向的URL,但show_program_client_path对应的路由仅支持GET方法,因此出现路由匹配错误。

解决方案

下面提供两种可行的修复方案:

方案一:控制器针对JS请求返回跳转逻辑

修改reminders_controller.rb的update方法,添加format.js处理,直接返回JS代码让浏览器执行跳转:

def update
  respond_to do |format|
    if @reminder.update(reminder_params)
      format.html { redirect_to show_program_client_path(@program.entity, program_id: @program.id, remove_modal: true), notice: "Reminders was successfully updated." }
      # 针对Ajax请求返回跳转JS
      format.js { 
        render js: "window.location.href='#{show_program_client_path(@program.entity, program_id: @program.id, remove_modal: true)}'"
      }
    else
      format.html { render :edit, status: :unprocessable_entity }
      format.json { render json: @reminder.errors, status: :unprocessable_entity }
      format.js { render js: "alert('更新失败');" }
    end
  end
end

方案二:前端Ajax成功回调手动跳转

1. 修改前端JS函数

在Ajax成功回调中直接执行页面跳转,同时将请求类型改为JSON:

function reminder_status(chk) {
  $.ajax({
    type: "PATCH",
    url: "/programs/<%=@program.code%>/reminders/"+$(chk).attr('id'), 
    dataType: "json",
    data: { reminder: {title : chk.checked} },
    success: function() {
      // 成功后跳转目标页面
      window.location.href = "<%= show_program_client_path(@program.entity, program_id: @program.id, remove_modal: true) %>";
    },
    error: function() {
      alert('更新失败,请重试');
    }
  });
}

2. 控制器添加JSON响应

def update
  respond_to do |format|
    if @reminder.update(reminder_params)
      format.html { redirect_to show_program_client_path(@program.entity, program_id: @program.id, remove_modal: true), notice: "Reminders was successfully updated." }
      format.json { render json: { success: true }, status: :ok }
    else
      format.html { render :edit, status: :unprocessable_entity }
      format.json { render json: @reminder.errors, status: :unprocessable_entity }
    end
  end
end
额外提示

注意到你传递的参数是reminder: {title : chk.checked},但复选框实际是控制reminder的status状态?如果是笔误,建议将参数改为reminder: {status: chk.checked},同时确保reminder_params允许status参数被修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:00:52