Rails中form_with提交表单后页面不跳转,报重定向相关错误
问题
在Rails项目的/new页面用form_with构建表单,点击提交后,服务器和Fiddler确认数据已发送,但页面始终停留在/new,没有跳转到/articles。试过重启服务器、更换浏览器,也测试了多种form_with写法(指定:articles、url: '/articles'、绑定@article并用articles_path等),问题依旧。
相关代码及日志
articles_controller.rb
class ArticlesController < ApplicationController def new @article = Article.new end def create render plain: params[:article].inspect end end
new.html.erb
<%= form_with(model: @article, method: :post, url: articles_path) do |f| %> <p> <%= f.label :title %><br/> <%= f.text_field :title %> </p> <p> <%= f.label :text %><br/> <%= f.text_area :text %> </p> <p> <%= f.submit %> </p> <% end %>
Rails服务器日志
Started POST "/articles" for 127.0.0.1 at 2023-03-22 15:58:47 +0300 Processing by ArticlesController#create as TURBO_STREAM Parameters: {"authenticity_token"=>"[FILTERED]", "article"=>{"title"=>"", "text"=>""}, "commit"=>"Create Article"} Rendering text template Rendered text template (Duration: 0.0ms | Allocations: 4) Completed 200 OK in 1ms (Views: 0.5ms | ActiveRecord: 0.0ms | Allocations: 442)
Firefox控制台错误
Error: Form responses must redirect to another location
解决方案
问题根源是Rails 7默认启用的Turbo框架。Turbo对表单提交的响应有严格要求:必须返回重定向,不能直接渲染文本或视图。你的create方法用render plain:返回了纯文本响应,不符合Turbo的规则,导致页面无法跳转。
有两种解决方式:
修改控制器返回重定向(推荐)
调整create方法,改为重定向到目标页面,比如文章列表页或详情页:def create @article = Article.new(article_params) if @article.save # 重定向到文章列表页 redirect_to articles_path, notice: '文章创建成功' else # 保存失败则回到新建页面,保留用户输入 render :new end end private # 新增参数过滤,符合Rails安全规范 def article_params params.require(:article).permit(:title, :text) end临时禁用Turbo(仅调试用)
如果只是想验证表单功能,不想用Turbo,可以在form_with中添加data: { turbo: false }:<%= form_with(model: @article, method: :post, url: articles_path, data: { turbo: false }) do |f| %> # 原有表单内容不变 <% end %>
内容的提问来源于stack exchange,提问作者Vladimir Lozitskiy
相关产品推荐
相关产品推荐

