コメント機能のajax化
前回のajax化の記事にてどんなものかある程度理解したので、この記事ではお気に入りボタンの実装を例としてしたが、今回はコメント機能の投稿と削除のajax化の備忘録として記載。
手順
①コントローラーの修正
②remote: true
の追加やclass
、id
の指定
③js.erbファイル
の追加
①コントローラーの修正
redirect先
を削除
修正前comments_controller.rb
class CommentsController < ApplicationController
def create
comment = current_user.comments.build(comment_params)
if comment.save
redirect_to board_path(comment.board), success: t('defaults.message.created', item: Comment.model_name.human)
else
redirect_to board_path(comment.board), danger: t('defaults.message.not_created', item: Comment.model_name.human)
end
↓このように修正。
修正後comments_controller.rb
class CommentsController < ApplicationController
def create
@comment = current_user.comments.build(comment_params)
@comment.save
end
②remote: true
の追加やclass
、id
の指定
コメントフォームにid:'new_comment'
、
テキストエリアにid:"js-new-comment-body"
を追加。
またform_with
からlocal: true
を削除。form_with
は元からremote :ture
となっているのでわざわざ新たに記入する必要はない。
エラーメッセージはformではなく後に出てくるjs.erbファイル
に記載する。
form.html.rb
<%= form_with model: comment,url: [board, comment],id:'new_comment' do |f|%>
<div class="form-group">
<%= f.label :body%>
<%= f.text_area :body,class:"form-control mb-3",id:"js-new-comment-body",row:4,placeholder: "コメント"%>
</div>
<%= f.submit t('defaults.post'),class:"btn btn-primary"%>
<%end%>
削除ボタンにclass: 'js-delete-comment-button'
とremote: true
を追加。
delete_button.rb
<%= link_to comment_path(comment),
class: 'js-delete-comment-button',
method: :delete,
data: { confirm: "コメントを削除します。よろしいですか?" },
remote: true do %>
<%= icon 'fa', 'trash' %>
<% end %>
③js.erbファイル
の追加
コメントviewファイル直下にcreate.js.erb
とdestroy.js.erb
を作成。
create.js.erb
# ↓既に表示されているエラーメッセージがあった場合は削除する
$("#error_messages").remove()
# ↓コメント作成処理の結果によって処理を分岐
<% if @comment.errors.present? %>
# ↓エラーがある、処理失敗時にはエラーメッセージのパーシャルを表示
$("#new_comment").prepend("<%= j(render('shared/error_messages', object: @comment)) %>")
<% else %>
# エラーがない、処理成功時には作成されたコメント内容をHTML要素として追加する
$("#js-table-comment").prepend("<%= j(render('comments/comment', comment: @comment)) %>")
# ↓コメント入力フォームのテキストは表示する必要がないので、空文字に置き換えて内容をクリアにする
$("#js-new-comment-body").val('')
<% end %>
destroy.js.erb
$("tr#comment-<%= @comment.id %>").remove()