轨道3未定义的方法'创造'的零:NilClass错误,而试图创建一个相关对象 [英] Rails 3 undefined method `create' for nil:NilClass error while trying create a related object

查看:233
本文介绍了轨道3未定义的方法'创造'的零:NilClass错误,而试图创建一个相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号,用户和个人资料,在一到一个关系,我想创建一个新的配置文件的用户,如果它尚不存在:

I have two models, User and Profile, in one-to-one relation and I am trying to create a new profile for a user if it does not exist yet:

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

unless user.profile.present?
  user.profile.create
end

但我得到一个错误:未定义的方法'创造'的零:NilClass

推荐答案

那么,两件事情。首先,我假设code是错误的,因为只有进入块如果配置文件是存在的(因此不能创建一个)。

Well, two things. Firstly, I assume the code is wrong, as that only enters the block if the profile is there (and hence can't create it).

if user.profile.blank?
  user.profile.create
end

看起来更正确的code。

looks like more correct code.

其次,当你使用HAS_ONE,你不使用.create喜欢你做的has_many。这是因为,相对于对象被直接返回,而不是一个代理方法像的has_many。等效方法是create_profile(或create_x其中x是对象)

Secondly, when you use a has_one, you don't use .create like you do with has_many. This is because the relation object is directly returned, and not a "proxy" method like a has_many. The equivalent method is create_profile (or create_x where x is the object)

因此​​,请尝试以下code:

Hence, try the following code:

if user.profile.blank?
  user.create_profile
end

这篇关于轨道3未定义的方法'创造'的零:NilClass错误,而试图创建一个相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆