Rails 7 创建新记录时路由错误:POST请求被识别为GET
Rails POST请求被识别为GET导致路由错误解决方案
问题现象
提交表单或点击"New user"链接时,出现路由错误:
No route matches [GET] "/home/new_user"
涉及代码
表单代码
<%= form_with model: @user, url: home_new_user_path, method: :post do |f|%> <%= hidden_field_tag :authenticity_token, form_authenticity_token %> <%= f.text_field :name, placeholder: "Enter name", class: 'form-content form-content w-100 p-1', autocomplete: "off" %> <%= f.text_field :email, placeholder: "Enter email", class: 'form-content form-content w-100 p-1', autocomplete: "off" %> <%= f.text_field :password, placeholder: "Enter password", class: 'form-content form-content w-100 p-1', autocomplete: "off" %> <%= f.text_field :password_confirmation, placeholder: "Enter password to confirm", class: 'form-content form-content w-100 p-1', autocomplete: "off" %> <%= f.submit %> <%end%>
路由配置(routes.rb)
post 'home/new_user', to: 'home#new_user'
控制器方法(home_controller.rb)
def new_user user_to_be_created = User.create!(name: params[:name], email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation]) end
访问链接代码
<%= link_to "New user", home_new_user_path, method: :post %>
原因及解决方法
1. link_to的POST依赖Rails UJS实现
Rails里link_to指定method: :post不是直接发送POST请求,而是靠Rails UJS(非侵入式JS)把GET请求转换成POST。如果页面没加载UJS,浏览器会默认发GET请求。
解决:
- Rails 5及更早版本,确保
application.js包含://= require rails-ujs - Rails 6+使用Webpacker时,在
application.js中导入并启动UJS:import Rails from "@rails/ujs" Rails.start()
2. 表单冗余代码与远程提交问题
你手动添加了authenticity_token,但form_with会自动生成这个字段,冗余代码可能引发异常。另外form_with默认是远程表单(remote: true),UJS未加载时会导致请求方式异常。
解决:
- 删除手动添加的
<%= hidden_field_tag :authenticity_token, form_authenticity_token %> - 如果不需要远程提交,显式设置
local: true:<%= form_with model: @user, url: home_new_user_path, method: :post, local: true do |f|%>
3. 路由不符合RESTful规范
当前路由home/new_user违反Rails RESTful约定,创建资源的标准动作是create,而非new_user,这种命名容易混淆逻辑,间接增加出错概率。
建议调整为RESTful风格:
修改routes.rb:
resources :users, only: [:new, :create]
对应控制器写create方法,视图链接改为new_user_path(GET显示表单),表单提交到users_path(POST创建用户),完全遵循Rails约定,减少错误。
4. 检查浏览器JS错误
打开浏览器开发者工具控制台,查看是否有UJS加载失败的报错,JS错误会导致无法完成请求方式转换。
内容的提问来源于stack exchange,提问作者TEJINDER SINGH
相关产品推荐
相关产品推荐

