Ruby on Rails 5.1使用Bootstrap模态框进行删除确认

3

我正在制作一个简单的博客应用程序,其中包含许多文章。我成功地为每篇文章创建了一个删除按钮,并使用浏览器的默认确认弹窗:

<%= link_to 'Delete' , article, method: :delete, data: { confirm: 'Are you sure?' } %>

我现在正尝试使用Bootstrap模态框来创建自定义的删除确认框。

Bootstrap模态框已经显示出来了,但是它却删除了错误的文章。它总是删除最上面(第一篇)的文章。

版本:

  • Bootstrap 4
  • Rails 5.1.4

代码:

application.js

// app/assets/javascripts/application.js

//= require rails-ujs
//= require jquery3
//= require popper
//= require bootstrap-sprockets
//= require_tree .

index.html.erb

<!-- app/views/articles/index.html.erb -->

<div class="container">
    <h1>My Blog</h1>

    <!-- Render Articles -->
    <%= render @articles %> 
</div>

_article.html.erb

<!-- app/views/articles/_article.html.erb -->

<div class="row">
  <div class="col-sm-8">
    <div class="card mb-3">
      
      <div class="card-body">
        <h4 class="card-title"><%= article.title %></h4>
        <p class="card-text"><%= @markdown.render(article.body).html_safe %></p>
      </div>

      <div class="card-footer">
        <!-- Delete Button showing the modal -->
        <button type="button" class="btn btn-outline-danger" 
             data-toggle="modal" data-target="#exampleModal">
          Delete
        </button>
      </div>

      <!-- Modal -->
      <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">

            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Delete Confirmation</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
              </button>
            </div>

            <div class="modal-body">
              Are you sure?
            </div>
            
            <!-- Delete button in the footer -->
            <div class="modal-footer">
              <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
              <%= link_to 'Delete', article, method: :delete, class: 'btn btn-outline-danger' %>
            </div>

        </div>
      </div>
    </div>
</div>

渲染视图:

这是文章视图:

Articles

删除模态框弹出,但删除了错误的内容!不知何故,所有删除按钮都指向第一篇文章。

Delete confirmation

我是 Ruby on Rails 的新手,请帮忙!


你可以使用JavaScript创建一个链接,并在模态框中使用JQuery的点击函数来放置它。https://dev59.com/B2445IYBdhLWcg3wnroi - Beengie
@Beengie能否详细说明一下?我对Web开发也是新手,如果您能花点时间写一个详细的答案将会很有帮助。感谢您的帮助! :) - Khang Vu
1个回答

3
您的所有模态框都有相同的ID:exampleModal,因此当您单击Delete按钮时,打开的是第一个exampleModal实例。

请按以下方式更改您的部分内容...

    <button type="button" class="btn btn-outline-danger" 
         data-toggle="modal" data-target="#exampleModal<%= article.id %>">

并且...

<div class="modal fade" id="exampleModal<%= article.id %>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

这样,正确且唯一的模态id将会被打开。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接