Ruby on rails 未定义的方法`user';零级:零级

Ruby on rails 未定义的方法`user';零级:零级,ruby-on-rails,Ruby On Rails,我有一个允许评论的发布系统。 我正在制作通知系统,并且正在收到此错误: CommentsController中的命名错误#创建 nil:NilClass的未定义方法“user” 我认为用户被定义为一个post属性,我正在调用post,所以应该可以 下面是create方法 def create @comment = Comment.new(comment_params) @comment.user_id = current_user.id respond_to do |fo

我有一个允许评论的发布系统。 我正在制作通知系统,并且正在收到此错误:

CommentsController中的命名错误#创建 nil:NilClass的未定义方法“user”

我认为用户被定义为一个post属性,我正在调用post,所以应该可以

下面是create方法

def create
    @comment = Comment.new(comment_params)
    @comment.user_id = current_user.id
    respond_to do |format|
      if @comment.save
        create_notification @post
        format.html { redirect_to request.referer, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end
应该注意的是,我在其中的一部分遵循了一个教程,它最初有一行“create_notification@post,@comment”,但后来创建了一个参数错误

这是创建通知的方法,错误在第二行

def create_notification(post)  
      return if post.user.id == current_user.id
      Notification.create(user_id: post.user.id,
                        notified_by_id: current_user.id,
                        post_id: post.id,
                        comment_id: comment.id,
                        notice_type: 'comment')
    end  
它从第二行开始,如果注释掉了,它将转到下一行

这是应用程序跟踪

app/controllers/comments_controller.rb:71:in `create_notification'
app/controllers/comments_controller.rb:33:in `block in create'
app/controllers/comments_controller.rb:31:in `create'
CommentsController中的NoMethodError#为创建未定义的方法“user” 零:零级


create_notification@post
中,
@post
nil
请确保已定义
@post
。例如
@post=post.find(params[:comment][:post\u id])

您正在将
@post
传递给您的
创建通知方法,但是您在哪里定义
@post
?注释与post相关联,这不是一回事,但我认为这就足够了。这是新评论表单的一部分:@post.id%>。它们在模型中也有关联。你知道当你假设时会发生什么吗?您的方法需要一个参数;在本例中,是一个Post对象。但是,您正在将nil传递给它,因为未定义
@post
。另外,在这种情况下,表单与传递给
create\u notification
方法的内容无关。你说得对,我知道我不应该假设事情和编程是非常技术性的,谢谢你的反馈。