コメント投稿機能に削除機能を追加したのですが、`destroy' for nil:NilClassと出てしまいます。
この場合コントローラーのdestroyアクションが(blog_id: params[nill]) = nillになるという解釈で合っていますでしょうか?
その場合、params[]内に何のidを代入すればよろしいでしょうか?
解決をお願いします。
### /controller/blog_comments_controller.rb class Public::BlogCommentsController < ApplicationController def create blog = Blog.find(params[:blog_id]) comment = current_user.blog_comments.new(blog_comment_params) comment.blog_id = blog.id comment.save redirect_to public_blog_path(blog) end def destroy BlogComment.find_by(id: params[:id], blog_id: params[:blog.id]).destroy redirect_to public_blog_path(blog) end private def blog_comment_params params.require(:blog_comment).permit(:comment) end end
### blogs_controller.rb class Public::BlogsController < ApplicationController before_action :authenticate_user!, except: [:index] def index @blogs = Blog.search(params[:search]) @blog = Blog.new end def create @blog = Blog.new(blog_params) @blogs = Blog.all @blog.user_id = current_user.id if @blog.save! redirect_to public_blogs_path(@blog), notice: 'Create succsessfuly' else render :create end end def show @blog = Blog.find(params[:id]) @blog_comments = @blog.blog_comments @blog_comment = current_user.blog_comments.new end def edit @blog = Blog.find(params[:id]) if @blog.user != current_user redirect_to public_blogs_path, alert: 'Invalid Access' end end def update @blog = Blog.find(params[:id]) if @blog.update!(blog_params) redirect_to public_blogs_path(@blog.id), notice: 'Update succsessfuly' else render :edit end end def destroy blog = Blog.find(params[:id]) blog.destroy redirect_to public_blogs_path, notice: 'Deleted succsessfuly' end private def blog_params params.require(:blog).permit(:title, :body, :blog_image_id) end end
### /public/blogs/show.html.erb <% @blog.blog_comments.each do |blog_comment| %> <li class="comment"> <div class="card"> <div class="card-body"> <div class="col-3"> <div class="comment-avatar"> <div class="avatar"> <%= attachment_image_tag @user, :profile_image, fallback: "no_image.jpg", :size =>'50x50' %> </div> </div> </div> <div class="comment-entry"><%= blog_comment.comment %></div> <div class="card-footer"> <%= link_to public_user_path(blog_comment.user) do %> <%= blog_comment.user.username %> <% end %> <%= blog_comment.created_at.strftime('%Y/%m/%d') %> <% if blog_comment.user == current_user %> <div> <%= link_to "削除", public_blog_blog_comment_path(blog_comment), method: :delete, class: "btn btn-danger pull-right" %> </div> <% end %> </div> </div> </div> </div> </li> <% end %>
### /migrate/create_blog_comments.rb class CreateBlogComments < ActiveRecord::Migration[5.2] def change create_table :blog_comments do |t| t.text :comment t.integer :user_id t.integer :blog_id t.timestamps t.timestamps end end end
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。