コメント投稿、削除のAjax化
実装内容
コメントの投稿、削除処理をajax(remote :true)で行う。
削除ボタンのaタグにはjs-delete-comment-buttonclassを付与。
ルーティング
commentsに削除を追加。
~ resources :users resources :boards do resources :comments, only: %i[create destroy], shallow: true collection do get :bookmarks end end resources :bookmarks, only: %i[create destroy] end
コメント投稿、削除のAjax化
コメント投稿フォームでの処理をajax化するので、form_withにlocal:true
→remote:true
へ変更。
form_withはデフォルトでremote:trueなので書かなくても良い
<!-- コメントフォーム --> <div class="row mb-3"> <div class="col-lg-8 offset-lg-2"> <%= form_with model: comment, url: [board, comment], id: 'new_comment' do |f| %> <%= render 'shared/error_messages', object: f.object %> <%= f.label :body %> <%= f.text_area :body, class: 'form-control mb-3', id: 'js-new-comment-body', placeholder: 'コメント' %> <%= f.submit '投稿', class: 'btn btn-primary' %> <% end %> </div> </div>
コメント削除ボタンのlink_toへremote:trueを追記
リンク先のpathを指定。
~ <% if current_user.own?(comment) %> <!--自分のコメントだけ編集アイコンを表示する--> <td class="action"> <ul class="list-inline justify-content-center" style="float: right;"> <li class="list-inline-item"> <a href="#" class='js-edit-comment-button' data-comment-id="<%= comment.id %>"> <%= icon 'fa', 'pen' %> </a> </li> <li class="list-inline-item"> <%= link_to comment_path(comment), method: :delete, remote: true, class: 'js-delete-comment-button' ,data: {confirm: 'よろしいですか'} do %> <%= icon 'fas', 'trash'%> <% end %> </a> </li> </ul> </td> <% end %> </tr>
comments_controllerの修正
redirect_backを削除
~ def create @comment = current_user.comments.build(comment_params) @comment.save end def destroy @comment = current_user.comments.find(params[:id]) @comment.destroy! end ~
jsファイルの作成
$("#error-messages").remove(); <% if @comment.errors.present? %> $("#new_comment").prepend("<%= j(render('shared/error_messages', object: @comment)) %>"); <% else %> $("#js-table-comment").prepend("<%= j(render('comments/comment', comment: @comment)) %>"); $("#js-new-comment-body").val(''); <% end %>
$("#comment-<%= @comment.id %>").remove();