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

后端 未结 1 782
不思量自难忘°
不思量自难忘° 2021-01-07 11:43

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         


        
相关标签:
1条回答
  • 2021-01-07 12:45

    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
    
    0 讨论(0)
提交回复
热议问题