どうもどハマりエンジニアです。
本日は前回のブックマーク機能のAjax化に引き続き、コメント(投稿・削除)のAjax化をしていきたいと思います。
①コントローラー
(comments_controller.rb)
def create
@comment = current_user.comments.build(comment_params)
@comment.save
def destroy
@comment = current_user.comments.find(params[:id])
@comment.destroy
end
②テンプレート
(comments/_form.html.erb) createアクションのための
<%= form_with model: comment, url: [board, comment],
remote: true, id: 'new_comment' do |f| %>
<%= f.label :body%>
<%= f.text_area :body, class: 'form-control mb-3', placeholder: 'コメント',
rows: "4", id: 'js-new-comment-body' %>
<%= f.submit '投稿', class: 'btn btn-primary' %>
<% end %>
・form_withのとろこで、remote:trueをつけること。
・id: 'new_comment' → エラーメッセージを表示させるための
・ id: 'js-new-comment-body' → createの時はidは必要なし
(shared/error_messages.html.erb)
<% if object.errors.any? %>
<div class = 'alert alert-warning', id="error_messages">
<ul>
<% object.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
・id='error_messages' → 付け加える!!
(comments/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 %>
$("#error_messages").remove() → エラーメッセージが表示された場合に、例えばコメントが作成された場合はエラーメッセージが消えたり、エラーメッセージが再び出た場合は一つ目のエラーメッセージが消え、二つ目のエラーメッセージが表示される。
2段落目からはエラーメッセージがあれば表示させるといった意味合い。prependは1番前に表示させるという意味。
$("#js-new-comment-body").val('') → コメントが作成された場合に、コメントフォームを空白にするためのもの。
(comments/_comment.html.erb)
<tr id="comment-<%= comment.id %>">
・
.
<%= link_to comment_path(comment),
class: 'js-delete-comment-button',
method: :delete,
data: { confirm: '削除してもよろしいですか?' },
remote: true do %>
<%= icon 'fa', 'trash' %>
<% end %>
remote: true を加える
(comments/destroy)
$("tr#comment-<%= @comment.id %>").remove()
以上でコメント(投稿・削除)のAjax化についての実装が完了しました。
次回は編集機能を実装していきます。