Ruby on rails 未定义的方法“posts';对于nil:NilClass错误
我得到这个错误: nil:NilClass的未定义方法“posts” 我有一个模型帖子,这是我的帖子管理员Ruby on rails 未定义的方法“posts';对于nil:NilClass错误,ruby-on-rails,controller,associations,Ruby On Rails,Controller,Associations,我得到这个错误: nil:NilClass的未定义方法“posts” 我有一个模型帖子,这是我的帖子管理员 def new @post = current_user.posts.build end def create @user = current_user @post = @user.posts.build(post_params) end 代码中的current\u user字段未设置,其值为nil。因此,当您尝试访问当前用户.posts时,它会转换为获取nil类对象的
def new
@post = current_user.posts.build
end
def create
@user = current_user
@post = @user.posts.build(post_params)
end
代码中的
current\u user
字段未设置,其值为nil
。因此,当您尝试访问当前用户.posts
时,它会转换为获取nil
类对象的posts。由于对于nil
类的对象没有这样的方法,我们得到了一个错误。您可以显示您的model user.rb和post.rb当前\u用户
为nil,您确定您使用了正确的方法并且用户已登录吗?您是否将放在\u操作:验证\u用户之前代码>在控制器中?(假设您使用的是Desive)和ps。您可以直接使用当前用户,无需将其存储在实例变量中。。。所以只要做:@post=current_user.posts.build(post_参数)