为什么我得到“未定义的方法”?
我有一个配置文件模型,并且一个用户 has_one 配置文件。
这是我的路线:
resources :users
resources :profiles
这是我的控制器中的显示方法:
def show
@profile = @user.profile
end
为什么当我尝试访问显示视图时会收到此错误:
NoMethodError in ProfilesController#show
undefined method `profile' for nil:NilClass
I have a profile model, and a user has_one profile.
Here's my route:
resources :users
resources :profiles
Here's the show method in my controller:
def show
@profile = @user.profile
end
Why do I get this error when I try to access the show view:
NoMethodError in ProfilesController#show
undefined method `profile' for nil:NilClass
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要初始化
@user
实例变量。你可能想做这样的事情:无聊的解释:实例变量(前面有
@
的变量)默认是nil
。它们实际上可以通过为其分配一个非零值来“实例化”。这里,@user
是一个实例变量,它指向nil,因为它还没有被分配任何东西。profile
在nil
的上下文中调用,它没有profile
方法,因此您会得到 no method 异常。这与局部变量相反,局部变量以小写字母开头,在这种情况下会引发局部变量未找到异常。You need to initialize the
@user
instance variable. You probably want to do something like this:Boring explanation: Instance variables (the ones with
@
in the front) arenil
by default. They can be de facto "instantiated" by just assigning a non-nil value to it. Here,@user
is an instance variable, and it points to nil because it hasn't been assigned anything.profile
is invoked in the context ofnil
, which doesn't have aprofile
method, so you get the no method exception. This is as opposed to local variables, starting with a lower-cased letter, which would in this case have raised a local variable not found exception.因为
@user
对象是nil
?您在尝试使用 @user 实例变量之前是否填充了它?Because
@user
object isnil
? Did you populate@user
instance variable before trying to use it?那是因为 @user 为零,你需要这样的东西
That is because the @user is nil, you need something like this