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
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).
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: