form_for定义关联的Rails中的第一个参数nil错误



我正在使用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控制器中的显示方法中添加@comment=comment.new

谢谢大家!

您正在创建一个新的注释。您应该:

A。在控制器中的某个位置放置@comment = Comment.new

B。立即用进行实例化

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

相关内容

最新更新