Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined local variable or method `destroy' for CommentsController:Class in my destroy comment method

I've added a comment feature in my app and so far everything's working fine until this error came up. What I did is that I added a delete comment feature. Everything shows normal when I fire up the server, but the problem comes in after I click the 'delete' button.

Error message

undefined local variable or method `destroy' for CommentsController:Class

Anyway, here's my code.

Comments controller

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comments_params)
    redirect_to post_path(@post)
  end

  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy
    #redirect_to post_path(@post)
  end

  private

  def comments_params
    params.require(:comment).permit(:body, :commenter, :user_id)
  end
end

Comment view partial

<div class='row'>
    <div class='comments col-md-6'>
        <p>
          <b><%= comment.commenter %>:</b>
          <p><span><%= comment.body %></span></p>
        </p>

        <%= button_to 'Delete', [comment.post, comment],
               method: :delete, data: { confirm: 'Are you sure?' }  %>

    </div>
</div>

Comment form

<div class='form-group col-md-5'>

<%= form_for([@posts, @posts.comments.build]) do |f| %>

    <div class="form-group">
        <%= f.label 'Add a comment' %><br>
        <%= f.text_area :body, class: 'form-control', rows: '3' %>
    </div>
      <%= f.hidden_field :commenter, value: current_user.name %>
      <%= f.hidden_field :user_id, value: current_user.id %>
    <div class="actions">
        <%= f.submit %>
        <div class='back-button'>
        </div>
    </div>
<% end %>

</div>

help would be greatly appreciated!

UPDATE:

This is the link to my github repo. just in case anyone would like to tinker on it.

https://github.com/ridata14/BlogApp

like image 939
StormTrooper Avatar asked Dec 31 '25 09:12

StormTrooper


1 Answers

OK, I looked at the repo. You have a comments table but no model. rails generate model Comment

like image 62
Jim Edelstein Avatar answered Jan 02 '26 00:01

Jim Edelstein