LoginSignup
1
1

More than 3 years have passed since last update.

非同期でコメント機能作ってみた

Last updated at Posted at 2021-01-12

今回は非同期通信を用いたコメント機能を実装していきたいと思います:eyes:

前提

・コントローラー作成済み
・モデル作成済み
・リレーション設定済み

それでは実装していきましょう:blush:

①viewを作成

views/comments/_comment.html.erb

  <p>コメント件数:<%= pet.comments.count %></p>
    <% pet.comments.each do |comment| %>
      <%= comment.user.full_name %>
        <%= comment.created_at.strftime('%Y/%m/%d') %><%= simple_format comment.comment %>
          <% if comment.user == current_user %>
            <div class="comment-delete">
              <%= link_to "削除", pet_comment_path(comment.pet, comment), method: :delete, remote: true %>
            </div>
          <% end %>
    <% end %>
    <div class="new-comment">
      <%= form_with(model:[pet, comment], remote: true) do |f| %>
        <%= f.text_area :comment, size:"90x5" ,placeholder: "コメントをここに" %>
          <%= f.submit "送信する" %>
      <% end %>
    </div>

②作成した部分テンプレートを呼び出す

 <div class="comments_<%= @pet.id %>">
     <%= render 'comments/comment', pet: @pet, comment: @comment %>
 </div>

③コントローラー編集

class CommentsController < ApplicationController
  def create
    @pet = Pet.find(params[:pet_id])
    comment = Comment.new(comment_params)
    comment.user_id = current_user.id
    comment.pet_id = @pet.id
    comment.save
    @comment = Comment.new
  end

  def destroy
    @pet = Pet.find(params[:pet_id])
    Comment.find_by(id: params[:id], pet_id: params[:pet_id]).destroy
    @comment = Comment.new
  end

  private

  def comment_params
    params.require(:comment).permit(:comment)
  end
end

④ jQueryの記述

rudy:comments/create.js.erb
$(".comments_<%= @pet.id %>").html("<%= j (render 'comments/comment', pet: @pet, comment: @comment) %>");
$("text_area").val("");
comments/destroy.js.erb
$(".comments_<%= @pet.id %>").html("<%= j (render 'comments/comment', pet: @pet, comment: @comment) %>");

注意::raising_hand:

部分テンプレートを呼び出したviewのコントローラーに

@comment = Comment.new
@comments = Comment.all

を記述するのを忘れないように!
これがないとコメントを呼び出せないよ:wink:

以上で非同期コメント完成!!

1
1
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
1