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

如何使用ERB为button_to删除按钮添加确认弹窗?

问题:为Rails button_to删除按钮添加确认弹窗失败

点击「Delete Post」按钮删除帖子时,希望弹出确认提示框,但尝试通过onclick函数实现该功能失败,相关代码如下:

<div class="card my-5">
  <div class="card-body">

    <h1 class="text-center"><%= @post.title %></h1>
    <hr>
    <div class="my-4">
      <%= simple_format(@post.content) %>
    </div>
    <% pre_like = @post.likes.find { |like| like.user_id == current_user.id} %>
    <% if pre_like %>
      <%= button_to 'Dislike', post_like_path(@post, pre_like), method: :delete %>
    <% else %>
      <%= button_to 'Like', post_likes_path(@post), method: :post, class: 'btn btn-primary' %>
    <% end %>
    <p><%= @post.likes.count %> <%= (@post.likes.count) == 1 ? 'Like' : 'Likes'%></p>
    <div class="btn-group">
      <%= link_to 'Back', posts_path, class: 'btn btn-primary' %>
      <% if @post.user_id == current_user.id %>
        | <%= button_to 'Edit', @post, class: 'btn btn-primary' %>
        | <%= button_to "Delete Post", onclick: "delete()", post_path, method: :delete, class:"btn btn-primary" %>
      <% end %>
    </div>
  </div>
</div>

问题原因

  1. button_to参数顺序错误:Rails的button_to方法要求第二个参数是路径,你把onclick选项放在了路径前面,导致参数解析异常
  2. 使用了错误的JS逻辑:delete()是JavaScript内置函数,直接调用无法实现确认弹窗,也不能阻止表单提交

解决方案

修正参数顺序,用return confirm()实现确认逻辑——当用户点击取消时,该语句返回false,会阻止表单提交:

| <%= button_to "Delete Post", post_path, method: :delete, class:"btn btn-primary", onclick: "return confirm('确定要删除这篇帖子吗?')" %>

逻辑说明:

  • button_to会生成隐藏表单,onclick事件返回false时,表单不会提交
  • 用户点击弹窗「确定」时,confirm()返回true,触发删除操作;点击「取消」时返回false,终止操作

内容的提问来源于stack exchange,提问作者Aathityan Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:55:23