0
0

More than 1 year has passed since last update.

【Rails】コメント機能Ajax実装③ 削除編

Last updated at Posted at 2022-06-27

【Rails】コメント機能をAjax実装① 準備編
【Rails】コメント機能Ajax実装② 投稿編

投稿したコメントをAjaxで削除します!
今回の目標の完成形はこちらです↓
ezgif.com-gif-maker.gif

Commentコントローラーにdestroyアクションを追加

comments_controller.rb
class CommentsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_comment, only: [:edit, :update, :destroy]
  before_action :set_post, only: [:create, :edit, :update]

  def create
    @comment = current_user.comments.new(comment_params)
    @comment.post_id = @post.id
    if @comment.save
      render "create", notice: "コメントを投稿しました"
    else
      redirect_to @comment.post
    end
  end

  # -------ここから追加-------
  def destroy
    if @comment.destroy
    render "destroy", notice: "コメントを削除しました"
    else
      redirect_to @comment.post
    end
  end
  # -------ここまで-------

  private
 #~~省略~~
end

ビューファイルを修正

今回扱うファイルは、show.html.erbにボタンを追加し、
新規でdestroy.js.erbを作成します。

.views
├── comments
│   ├──_comments.html.erb
│   ├──_form.html.erb
│   ├──create.js.erb
│   └──destroy.js.erb(←今回 追加するファイル)
│ 
└── posts
    └──show.html.erb

Viewファイルに削除ボタンを追加

views/comments/_comments.html.erb
<% post.comments.each do |comment| %>
  <div id="comment_<%= comment.id %>" class="comment pb-3 d-flex gap-3">
    <div class="profile_icon">
      <%= image_tag comment.user.profile_icon.url, class: 'rounded-circle' %>
    </div>
    <div class="p-3 border flex-grow-1 rounded">
      <div class="d-flex gap-3 pb-3">
        <div class="fw-bold"><%= comment.user.name %></div>
        <div><%= comment.created_at %></div>
      </div>
      <div>
        <p class="pb-3"><%= comment.body %></p>
        <!------ここから追加------->
          <% if  user_signed_in? && comment.user_id == current_user.id %>
            <div>
              <%= link_to "削除", post_comment_path(comment.post, comment), method: :DELETE, remote: true, class: "btn btn-sm btn-outline-danger" %>
            </div>
          <% end %>
             <!------ここまで------->
      </div>
    </div>
  </div>
<% end %>

link_to に remote: trueを入れ非同期に切り替えます!
また、削除ボタンは投稿したユーザーのみに表示させたいので、<% if user_signed_in? && comment.user_id == current_user.id %>を追加します。

JavaScriptファイルを作ります

views/comments/destroy.js.erb
$('#comment_<%= @comment.id %>').remove();

以上で、削除機能が実装できました。
次回の記事で更新機能を追加します!

関連記事

【Rails】コメント機能をAjax実装① 準備編
【Rails】コメント機能Ajax実装② 投稿編
【Rails】コメント機能Ajax実装④ 更新編

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0