How can I create an association record if it does not exist when it is accessed?

associations, model, ruby-on-rails

Solution

You could use `after_initialize` callback:

class User
  # ..
  after_initialize do
    self.profile ||= self.build_profile
  end
  # ..
end

Problem

How would I do this pseudocode? I want to prevent for example "undefined method zip_code for nil class" as I have existing users with our a profile yet. So when user.profile is called I would like to create it if it does not exist. ``` class User < ActiveRecord::Base ... # Associations: has_one :profile # example call current_user.profile.zip_code def profile if self.profile exists <-- use super? self.profile else # create association record and return it self.build_profile.save self.profile end end ... end ```

Original source