简体   繁体   中英

undefined method `create' for nil:NilClass when trying to create profile in user model

I searched and found this Rails 3 undefined method `create' for nil:NilClass error while trying create a related object but that solution is also giving error - stack level too deep hence asking it on SO.

I have a user model and profile model with belongs_to and has_one relationship.

In my user.rb model I have

after_create :create_profile

def create_profile
  self.profile.create
end

but this is giving "undefined method `create' for nil:NilClass" at the self.profile.create line. The user is also not getting created nor the profile

after_create :create_profile is just enough, not necessary to define create_profile method, it's provided by rails.

Example:

class User < ActiveRecord::Base
  has_one      :profile
  after_create :create_profile
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM