I’m using devise to do the new user registration. Right after a new user is created, I would also like to create a profile for that user.
My create method in the registrations_controller.rb is as follows:
class RegistrationsController < Devise::RegistrationsController
def create
super
session[:omniauth] = nil unless @user.new_record?
# Every new user creates a default Profile automatically
@profile = Profile.create
@user.default_card = @profile.id
@user.save
end
But, it is not creating a new Profile and neither is the field for @user.default_card is being filled in. How can I create a new Profile automatically upon each new user registration with devise?
I would put this functionality into an
before_createcallback function on the user model since it is essentially model logic, would only not add another save call and is just generally more elegant.One possible reason why your code is not working is that
@profile = Profile.createis not executed successfully because it is failing validations or something. This would result in@profile.idbeingniland thus@user.default_cardisnil.Here is how I would implement this:
In your code(or mine), you can always put a simple
putsto check if the new profile is getting created. i.e.puts (@profile = Profile.create)