前提
・CRUD処理の実装はOK
・Bootstorapが導入済みである
開発環境
Ruby2.6.3
Rails5.2.5
Bootstrap4
目標
# 前後の記述は省略
<%= link_to "削除", post_path(post), method: :delete, data: { confirm: "削除しますか?" } %>
上記のように記述した時に出る削除確認ダイアログ
これだとちょっと味気ないので
Bootstrapを使ってこんな感じにしていきます。
実装方法
BootstrapのModalのページのコードを利用していきます。
# ページに表示されるボタン
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal">削除</button>
# 確認用のモーダル
<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">削除確認</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
# モーダルのbody部分、確認メッセージなど入れます
<div class="modal-body">削除しますか?</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">やめる</button>
<%= link_to "削除", post_path(post), method: :delete, class: "btn btn-danger" %>
</div>
</div>
</div>
</div>
以上の記述で上の画像のような確認画面になると思います。
ボタンの色などは適宜自分の好きな色に変えています。
ここまでは問題なく実装できたのですが、以下私が躓いた所です。
繰り返し処理でデータを表示している場合、上記の記述のままだと一番目のデータだけが削除の対象になってしまいました。(ページに表示されているモーダルのトリガーとなる削除ボタンにpost.idの指定がないからだと思います)
なので、どのデータを削除するのかIDを追加してあげる必要がありました。
# ページに表示されるボタン
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal<%= post.id %>">削除</button>
# 確認用のモーダル
<div class="modal fade" id="exampleModal<%= post.id %>" 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">削除確認</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
# モーダルのbody部分、確認メッセージなど入れます
<div class="modal-body">削除しますか?</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">やめる</button>
<%= link_to "削除", post_path(post), method: :delete, class: "btn btn-danger" %>
</div>
</div>
</div>
</div>
2ヶ所に<%= post.id %>を追加しています。
まずはモーダルを表示するためのトリガーとなる削除ボタンのdata-target部分。
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal<%= post.id %>">削除</button>
あとはモーダルのid部分です。
<div class="modal fade" id="exampleModal<%= post.id %>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
これで繰り返し処理をしても指定したデータを削除することができます。
他にも色々なタイプのモーダルがあるのでいずれ使ってみたいです。
以上です。