Jonton Jonton - 7 months ago 22
Ruby Question

form_for first argument nil error in Rails with defined associations

I'm building a simple Blog application using Rails and I'm trying to create the ability to submit a comment for a post. However, I keep getting this error


First argument in form cannot contain nil or be empty


<h3> Submit a Comment </h3>

<%= form_for [@post, @comment] do |c| %>
//Error is here, @comment appears to be nil and I'm not sure why
//(I've checked both cases)

<%= c.label :body, "Comment: " %>
<br />
<%= c.text_area :body %>


I've checked the other posts that had a similar issue but couldn't find a solution. Any help would be greatly appreciated

class CommentsController < ApplicationController

def create
@post = Post.find params[:post_id]

comment_params = params.require(:comment).permit(:body)

@comment = Comment.new comment_params
@comment.post = @post
# Why is my comment nil?

if @comment.save
redirect_to post_path(@post), notice: "Comment successful"
else
flash[:alert] = "Comment unsuccessful. Please do not enter an empty comment"
render "/posts/show"
end

end

def destroy
# To be implemented
end

end


EDIT: Solved, forgot to add @comment = Comment.new in the show method in my Post controller

Thanks everyone!

Answer

You're creating a new comment. You should either:

A. Have @comment = Comment.new somewhere in your controller

OR

B. Instantiate it right then and there with

form_for [@post, Comment.new] do |c| #...