Tamik Soziev
Tamik Soziev

Reputation: 14798

Rails 3 undefined method `create' for nil:NilClass error while trying create a related object

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

But I am getting an error: undefined method `create' for nil:NilClass

Upvotes: 1

Views: 2206

Answers (1)

Joe Pym
Joe Pym

Reputation: 1836

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

looks like more correct code.

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)

Hence, try the following code:

if user.profile.blank?
  user.create_profile
end

Upvotes: 9

Related Questions