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

Rails命名空间中带确认提示的Delete功能失效问题排查

核心原因分析

Rails 6+ 默认使用 Hotwire Turbo 替代了传统的 rails-ujs,原来的 data: { confirm: ... } 和 method: :delete 逻辑需要适配Turbo的规则;同时需先确认命名空间路由配置是否正确。

步骤1:验证命名空间路由配置

首先检查 config/routes.rb 是否正确定义了命名空间资源:

namespace :living_muay_thai do
  resources :students
end

运行 rails routes | grep student 确认存在DELETE路由:

DELETE /living_muay_thai/students/:id(.:format) living_muay_thai/students#destroy

步骤2:适配Turbo的删除链接写法

将原有的 data: { confirm: ... } 替换为Turbo支持的 data: { turbo_confirm: ... },同时确保路由辅助方法/对象引用正确:

写法1:直接传递模型对象

<%= link_to 'Destroy', s, 
            method: :delete, 
            data: { turbo_confirm: 'Are you sure?' } %>

Rails会自动识别 LivingMuayThai::Student 实例对应的命名空间路由。

写法2:使用命名空间路由辅助方法

<%= link_to 'Destroy', living_muay_thai_student_path(s), 
            method: :delete, 
            data: { turbo_confirm: 'Are you sure?' } %>

(优先用 _path 而非 _url,除非需要绝对路径)

步骤3:确认Turbo已正确加载

检查以下配置确保Turbo正常运行:

  1. config/importmap.rb 中包含:
    pin "turbo-rails", to: "turbo.min.js", preload: true
    
  2. app/javascript/application.js 中导入:
    import "@hotwired/turbo-rails"
    
  3. app/views/layouts/application.html.erb 中加载Turbo脚本:
    <%= javascript_importmap_tags %>
    

额外优化:控制器跳转更明确

将控制器中 redirect_to(action: "index") 改为命名空间索引路由,避免歧义:

def destroy
  @student = LivingMuayThai::Student.find(params[:id])
  @student.destroy
  flash[:notice] = "#{@student.fname} #{@student.lname} has been deleted."
  redirect_to living_muay_thai_students_path
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:33:35