我收到此错误:
未定义的方法`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
您的代码中的current_user
字段未设置,并且值为nil
。因此,当您尝试访问current_user.posts
时,它会转换为获取nil
类对象的帖子。由于nil
class的对象没有这样的方法,我们得到一个错误。