I have a simple method that check for an existing User and if not found it will create it and will create also a Profile object.
Since the Profile requires the user_id to be saved, I need somehow to initialize the User with an ID if it does not exist.
I ended up with something like this, but this is not presetting a user_id when initialized the user.
def create_or_update_user(user)
user_object = User.find_or_initialize_by_external_id(user['external_id'])
if user_object.new_record?
user_profile = user_object.build_profile(params)
end
user_object.save
end
Any idea how can I set the ID when initialized the User record?
I dont think you can, and even so I dont think you should. If you assign an
idto your user without creating a record, theres a chance thatidmay be taken by the time you finally save it.Whats wrong with saving the user, then building and saving the profile?