Jonton Jonton - 2 years ago 79
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_params = @post
# Why is my comment nil?

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


def destroy
# To be implemented


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

Thanks everyone!

Answer Source

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

A. Have @comment = somewhere in your controller


B. Instantiate it right then and there with

form_for [@post,] do |c| #...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download