comments_controller.rb
def create
@comment = current_user.comments.build(comment_params)
@comment.save
end
def destroy
@comment = current_user.comments.find(params[:id])
@comment.destroy!
end
変更点としては
・redirectの処理を消す。
・commentをインスタンス変数に変更
comments/_form.html.erb
<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| %>
#form_withはデフォルトでremote: trueなので明示的に記載しなくても良い
<%= f.label :body %>
<%= f.text_area :body, class: 'form-control mb-3', id: 'js-new-comment-body', row: 4, placeholder: Comment.human_attribute_name(:body) %>
<%= f.submit t('defaults.post'), class: 'btn btn-primary' %>
<% end %>
</div>
</div>
comments/_comment.html.erb(一部抜粋)
<%= link_to comment_path(comment),
class: 'js-delete-comment-button',
method: :delete,
data: { confirm: t('defaults.message.delete_confirm') },
remote: true do %> #remote: trueを記載してajax化
<%= icon 'fa', 'trash' %>
<% end %>
create.js.erb
$("#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 %>
destroy.js.erb
$("tr#comment-<%= @comment.id %>").remove()
#<!-- removeメソッドでコメントを削除 -->