Rails 3 undefined方法`create'for nil:尝试创建相关对象时出现NilClass错误

Tam*_*iev 1 activerecord ruby-on-rails ruby-on-rails-3

我有两个模型,用户和配置文件,一对一的关系,我试图为用户创建一个新的配置文件,如果它还不存在:

user = User.includes(:profile).find( params[:user_id] )

unless user.profile.present?
  user.profile.create
end
Run Code Online (Sandbox Code Playgroud)

但是我收到一个错误:nil的未定义方法`create':NilClass

Joe*_*Pym 9

好吧,有两件事.首先,我假设代码是错误的,因为只有在配置文件存在时才进入块(因此无法创建它).

if user.profile.blank?
  user.profile.create
end
Run Code Online (Sandbox Code Playgroud)

看起来更正确的代码.

其次,当你使用has_one时,你不要像使用has_many一样使用.create.这是因为直接返回了关系对象,而不是像has_many这样的"代理"方法.等效方法是create_profile(或create_x,其中x是对象)

因此,请尝试以下代码:

if user.profile.blank?
  user.create_profile
end
Run Code Online (Sandbox Code Playgroud)