nil的未定义方法`user':NilClass

时间:2017-07-06 15:44:03

标签: ruby-on-rails

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

CommentsController中的NoMethodError #create nil的未定义方法`user':NilClass

我认为用户被定义为post属性,我正在调用帖子,所以它应该没问题。

这是创建方法

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”这一行,但之后会产生一个参数错误。

这是方法create_notification,错误在第二行

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'

1 个答案:

答案 0 :(得分:2)

   CommentsController中的NoMethodError #create undefined method`user'对于   零:NilClass

create_notification @post@postnil确保您已定义@post。例如@post = Post.find(params[:comment][:post_id])