投稿したコメントを削除できるようにしたいのですが、下記のコードを入れると undefined method "image_url" for nil:NilClass
という別のところでエラーが出ます。
プロジェクトの構造としては、postsという写真投稿機能があり投稿された写真の詳細ページ(posts/show.html.erb)にコメント欄とコメント一覧を設置しています。
↓deleteのコード
<% if logged_in? && comment.user == current_user %> <p><%= link_to '削除する', comment_path(comment), method: :delete, data: { confirm: "本当に削除しますか?" }, class: "comment-delete" %></p> <% end %>
↓エラーが出るコード
<div class="well img-well"> <%= image_tag @post.image_url, class: "main-img" %> <%= link_to '削除する', post_path(@post), method: :delete, data: { confirm: "本当に削除しますか?" } %> </div>
↓comments_controller.rb
before_action :correct_user, only: [:destroy] def create @post = Post.find(params[:comment][:post_id]) @comment = @post.comments.build(comment_params) @comment.user_id = current_user.id if @comment.save flash[:success] = 'コメントを投稿しました。' redirect_to post_path(@post) else flash.now[:danger] = 'コメントを投稿できませんでした。' render "posts/show" end end def destroy @comment.destroy redirect_to post_url end private def correct_user @comment = current_user.comments.find_by(id: params[:id]) unless @comment redirect_to post_url end end
↓posts_controller.rb
def show @post = Post.find_by(id: params[:id]) @comment = Comment.new end
よろしくお願いします。
追記
コメント削除のリンクを押せば削除はできているようなのですが、そこから画面を再表示する際にエラーが出ているようです。
回答1件
あなたの回答
tips
プレビュー