我正在使用Rails构建一个简单的博客应用程序,并且我尝试创建为帖子提交评论的功能。但是,我一直收到此错误
表单中的第一个参数不能包含nil或为空
<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 %>
我已检查过其他有类似问题但无法找到解决方案的帖子。任何帮助将不胜感激
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
编辑:解决了,忘了在我的Post控制器的show方法中添加@comment = Comment.new
谢谢大家!
答案 0 :(得分:3)
您正在创建新评论。你应该:
一个。在控制器的某个地方@comment = Comment.new
OR
B中。然后用
实例化它form_for [@post, Comment.new] do |c| #...