为什么我会得到“未定义方法”?

时间:2022-08-22 22:44:11

I have a profile model, and a user has_one profile.

我有一个概要文件模型,以及一个用户has_one概要文件。

Here's my route:

这是我的路线:

resources :users
resources :profiles

Here's the show method in my controller:

这是我的控制器中的show方法:

def show
  @profile = @user.profile
end

Why do I get this error when I try to access the show view:

当我试图访问show view时,为什么会出现这个错误:

NoMethodError in ProfilesController#show

undefined method `profile' for nil:NilClass

3 个解决方案

#1


1  

You need to initialize the @user instance variable. You probably want to do something like this:

您需要初始化@user实例变量。你可能想做这样的事情:

def show
  @user = User.find(params[:id])
  @profile = @user.profile
end

Boring explanation: Instance variables (the ones with @ in the front) are nil 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 of nil, which doesn't have a profile 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.

无聊的解释:实例变量(前面有@的变量)默认为nil。它们可以通过为其分配非nil值来实际“实例化”。在这里,@user是一个实例变量,它指向nil,因为它没有分配任何东西。配置文件在nil上下文中被调用,nil没有配置文件方法,所以您会得到no方法异常。这是相对于局部变量的,从小写字母开始,在本例中,这将引发局部变量,而不是异常。

#2


0  

Because @user object is nil? Did you populate @user instance variable before trying to use it?

因为@user对象是nil?在尝试使用它之前,您是否填充了@user实例变量?

#3


0  

That is because the @user is nil, you need something like this

因为@user是nil,你需要这样的东西

def show
  @user = User.find(params[:id]) 
  @profile = @user.profile
end

#1


1  

You need to initialize the @user instance variable. You probably want to do something like this:

您需要初始化@user实例变量。你可能想做这样的事情:

def show
  @user = User.find(params[:id])
  @profile = @user.profile
end

Boring explanation: Instance variables (the ones with @ in the front) are nil 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 of nil, which doesn't have a profile 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.

无聊的解释:实例变量(前面有@的变量)默认为nil。它们可以通过为其分配非nil值来实际“实例化”。在这里,@user是一个实例变量,它指向nil,因为它没有分配任何东西。配置文件在nil上下文中被调用,nil没有配置文件方法,所以您会得到no方法异常。这是相对于局部变量的,从小写字母开始,在本例中,这将引发局部变量,而不是异常。

#2


0  

Because @user object is nil? Did you populate @user instance variable before trying to use it?

因为@user对象是nil?在尝试使用它之前,您是否填充了@user实例变量?

#3


0  

That is because the @user is nil, you need something like this

因为@user是nil,你需要这样的东西

def show
  @user = User.find(params[:id]) 
  @profile = @user.profile
end