前提・実現したいこと
コメントの非同期通信についての質問です。
非同期通信にてコメント投稿・削除ができるようにしたいのですが、うまく動作しません。
・現状削除はうまく非同期でできています。
・投稿のみ非同期通信でうまくいきません。
・投稿の詳細ペー是でのコメント投稿となります。
該当のソースコード
comments/_index.html.erb
<% if comments.present? %> <% comments.each do |comment| %> <div class='comment-context'> <li> <% if comment.user.avatar.attached? %> <%= image_tag(comment.user.avatar, class:"avatar-post", id:"avatar-post") %> <% end %> <%= link_to comment.user.name, user_path(comment.user.id) %> : <%= comment.text %></li> </div> <% if user_signed_in? && current_user.id == comment.user.id %> <%= link_to "Delete", post_comment_path(comment.post_id, comment.id), method: :delete, remote: true, data: { confirm: "You sure?" }, class: 'btn btn-danger btn-sm', id: 'delete_btn' %> <% end %> <% end %> <% else %> <div class="comment-do" id="comment-do"> NO COMMENT YET </div> <% end %>
comments/index.js.erb
$("#comments").prepend("<%= redirect_back(fallback_location: root_path, { comments: @comment.post.comments }) %>") $("form-talk").val('')
routes.rb
Rails.application.routes.draw do resources :posts do resources :comments, only: [:index, :create, :destroy] post 'add' => 'likes#create' delete '/add' => 'likes#destroy' end end
comments_controller
class CommentsController < ApplicationController before_action :authenticate_user! def create @post = Post.find(params[:post_id]) #① @comment = Comment.new(comment_params) @comment.user_id = current_user.id #③ if @comment.save redirect_back(fallback_location: :root_path) end end def destroy @post = Post.find_by(params[:id]) @comment = Comment.find(params[:id]) if @comment.destroy redirect_back(fallback_location: root_path) end end private def comment_params params.require(:comment).permit(:text).merge(user_id: current_user.id, post_id: params[:post_id]) end end
posts_controller/show
def show @comments = @post.comments.includes(:user) @comment = Comment.new @user = @comment.user @like = Like.new end
補足情報(FW/ツールのバージョンなど)
'rails', '~> 6.0.0'
ruby '2.6.5'
javascrip
ここにより詳細な情報を記載してください。
あなたの回答
tips
プレビュー