①投稿機能コントローラを編集する
②ビューファイルの表示箇所を編集する
③js.erbファイルを作成する
①投稿機能コントローラを編集する
def create
@comment = current_user.comments.build(comment_params)
@comment.save
end
#コメント更新一覧アクション
def update
@comment = current_user.comments.find(params[:id])
@comment.update(comment_params)
end
#コメント更新フォームアクション
def edit
@comment = current_user.comments.find(params[:id])
end
#コメント削除アクション
def destroy
@comment = current_user.comments.find(params[:id])
@comment.destroy
end
②ビューファイルの表示箇所を編集する
[削除ボタンを押したときのajax]
comments/_comment.html.erbファイル
<%= link_to comment_path(comment),
class: 'js-delete-comment-button',
method: :delete,
remote: true do %>
<%= icon 'fas', 'trash' %>
<% end %>
[作成ボタンを押したときのajax]
comments/_form.erbファイル
<%= form_with model: [board, comment], class: 'js-new_comment' do |f| %>
③js.erbファイルを作成する
create.js.erb
$("#error_messages").remove()
<% if @comment.errors.present? %>
$(".js-new-comment").prepend("<%= j(render('shared/error_messages', object: @comment)) %>")
<% else %>
$("#js-table-comment").prepend("<%= j(render('comment', comment: @comment)) %>")
$("#js-new-comment-body").val('')
<% end %>
destroy.js.erb
$("tr#comment-<%= @comment.id %>").remove()
参考文献:https://qiita.com/jackie0922youhei/items/4f53047489cff3471f66