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

Ruby on Rails中create动作执行后未触发页面重定向问题

问题根因

出现这个问题的核心原因是Rails的form_with表单助手默认开启异步AJAX提交,提交请求时携带的是JS格式请求标识,不会触发整页跳转逻辑。
从你贴的日志也能验证:正常HTML重定向会返回302 Found状态码,但你的请求最终返回的是Completed 200 OK,说明控制器没有匹配到正确的响应格式,日志里打印的重定向记录是HTML分支的执行日志,但实际返回给浏览器的是适配AJAX请求的200响应,浏览器不会执行整页跳转。
你之前重写respond_to块、修改redirect_to逻辑都不生效,也是因为请求根本没有走到你预期的HTML重定向分支。

解决方案

二选一即可:

  • 方案1:关闭表单异步提交,使用普通整页提交
    给form_with添加local: true参数,强制表单走传统HTML提交逻辑:

    <%= form_with(model: event, local: true) do |form| %>
      ...
      <div class="actions">
        <%= form.submit %>
      </div>
    <% end %>
    

    修改后提交请求会匹配控制器的format.html分支,正常返回302重定向响应,浏览器会自动跳转到事件详情页。

  • 方案2:保留异步提交能力,补充JS格式响应逻辑
    如果你需要无刷新提交的交互体验,就在控制器的respond_to块中补充format.js分支,通过JS脚本触发跳转:

    # POST /events or /events.json
    def create
      @event = Event.new(event_params)
    
      respond_to do |format|
        if @event.save
          UserMailer.event_reminder(current_user)
          format.html { redirect_to @event, notice: "Event was successfully created." }
          format.json { render :show, status: :created, location: @event }
          # 新增JS响应,异步提交成功后执行页面跳转
          format.js { render js: "window.location.href = '#{event_url(@event)}'" }
        else
          format.html { render :new, status: :unprocessable_entity }
          format.json { render json: @event.errors, status: :unprocessable_entity }
          # 新增失败场景的JS响应
          format.js { render js: "alert('事件创建失败,请检查填写的内容')" }
        end
      end
    end
    

内容的提问来源于stack exchange,提问作者Top Text - Bottom Text

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:27:20