未定义的方法`posts'为nil:NilClass错误

问题描述 投票:0回答:1

我收到此错误:

未定义的方法`posts'为nil:NilClass

我有一个模型Post,这是我的PostsController

def new
  @post = current_user.posts.build
end

def create 
  @user = current_user 
  @post = @user.posts.build(post_params)
end
ruby-on-rails controller associations
1个回答
1
投票

您的代码中的current_user字段未设置,并且值为nil。因此,当您尝试访问current_user.posts时,它会转换为获取nil类对象的帖子。由于nilclass的对象没有这样的方法,我们得到一个错误。

© www.soinside.com 2019 - 2024. All rights reserved.