fuskie
fuskie

Reputation: 85

How to add comments

I'm trying to add comments to post model. This is my comments_controller so far:

class CommentsController < ApplicationController

    before_action :find_post

    def index
        @comments = @post.comments.order('id')
    end

    def new
        @comment = @post.comments.new
    end

    def create
        @comment = @post.comments.build(params[:comment])
        @comment.user = current_user
        @comment.save
        redirect_to post_path(@post)
    end

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

    def find_post
        @user = current_user
        @post = @user.posts.find(params[:post_id])
    end
end

I get this error:

NoMethodError in CommentsController#new undefined method `posts' for nil:NilClass

as you can see I'm new to programming. Thanks for help!:)

Upvotes: 0

Views: 131

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30453

Probably you get the error when you are not signed in. Method find_post is called every time because of before_action :find_post. If you are not signed in, then current_user is nil, and you call posts for nil.

Upvotes: 1

Related Questions