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

Rails 6.1+Hotwire登录表单提交报Form responses must redirect错误如何解决

问题原因

Rails 6.1 集成 Hotwire 后,form_with 默认开启 Turbo 异步提交,Turbo 对表单提交的响应格式有严格要求:成功提交必须返回 303 重定向,失败提交必须返回 422 状态码的响应,否则就会触发 Form responses must redirect to another location 报错。

可用解决方案

方案一:禁用 Turbo 表单提交(最快修复)

如果不需要用到 Turbo 异步交互特性,直接给表单添加 local: true 参数,走传统同步提交逻辑即可:

<%= form_with url: retailer_log_in_path, class: 'box', local: true do |f| %>
<!-- 其余表单内容保持不变 -->
<% end %>

方案二:适配 Turbo 响应规则(保留 Turbo 特性)

修改 Controller 逻辑,让响应符合 Turbo 要求即可:

  1. 登录成功的重定向显式指定 303 状态码(see_other)
  2. 登录失败渲染页面时显式指定 422 状态码(unprocessable_entity)

修改后的 Controller 代码如下:

def create
  retailer = Retailer.find_by(email: params[:email])
  if retailer.present? && retailer.authenticate(params[:password])
    session[:retailer_id] = retailer.id 
    # 显式指定303状态码
    redirect_to store_index_path, status: :see_other
  else
    flash.now[:alert] = 'Invalid email or password'
    # 显式指定422状态码
    render :new, status: :unprocessable_entity
  end
end

补充说明

你之前注释掉所有 create 逻辑仅保留 puts 输出时仍报错,是因为该场景下 Controller 没有返回任何合法响应,Turbo 无法识别自然会抛出异常,属于正常情况,按上述两种方案修改后即可恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:09:01