icecreamrabbit
icecreamrabbit

Reputation: 207

Comment form not working? (Ruby on Rails) undefined method `comments' for nil:NilClass

Hello helpful kind souls.

I am getting the 'undefined method `comments' for nil:NilClass' error when I try to submit a new comment. It highlights this part of the user controller :

def create
    @comment = @user.comments.build(comment_params)
    @comment.user = current_user

My comments controller:

class CommentsController < ApplicationController
def show
    @comment = Comment.find(params[:id])
  end

  def create
    @comment = @user.comments.build(comment_params)
    @comment.user = current_user

   if @comment.save
      redirect_to users_show_path, notice: 'Comment submitted!'
    else
      render 'users/show'
    end
  end

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

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

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

end

My user model includes has_many :comments and my comments model has belongs_to :user

Where do I need to look to correct this error? Thanks!

Upvotes: 0

Views: 203

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Well, where you have defined the value @user ? as I am seeing you didn't, In Ruby, if you use instance variables before defining them, they will simply give you nil object in return. Finally, you are calling the association method comments on the nil object. That's why the exception you got.

So, set the @user to an User instance first then call comments on it.

Upvotes: 1

Related Questions