LoginSignup
1
0

More than 1 year has passed since last update.

Railsでコメント機能のajax化

Posted at

コメント機能のajax化

前回のajax化の記事にてどんなものかある程度理解したので、この記事ではお気に入りボタンの実装を例としてしたが、今回はコメント機能の投稿と削除のajax化の備忘録として記載。

手順
①コントローラーの修正
remote: trueの追加やclassidの指定
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の追加やclassidの指定

コメントフォームに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.erbdestroy.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()
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0