Create another model with a new user registration in development

I use devise to register a new user. Immediately after creating a new user, I would also like to create a profile for this user.

My create method in registrations_controller.rb looks like this:

 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 does not create a new profile, and the field for @ user.default_card is not populated. How can I create a new profile automatically with each new user registration during development?

+4
source share
2 answers

I would include this functionality in the before_create callback function in the user model, since it is essentially the model logic, will not add another save call, and will usually be more elegant.

One of the possible reasons why your code is not working is because @profile = Profile.create not running successfully because it is not checking or something else. This will cause @profile.id be nil and thus @user.default_card will be nil .

Here is how I could implement this:

 class User < ActiveRecord::Base ... before_create :create_profile def create_profile profile = Profile.create self.default_card = profile.id # Maybe check if profile gets created and raise an error # or provide some kind of error handling end end 

In your code (or mine) you can always put a simple puts to check if a new profile is being created. those. puts (@profile = Profile.create)

+6
source

Another method on similar lines is this (use the build_profile method):

 class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :async, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:facebook] has_one :profile before_create :build_default_profile private def build_default_profile # build default profile instance. Will use default params. # The foreign key to the owning User model is set automatically build_profile true # Always return true in callbacks as the normal 'continue' state # Assumes that the default_profile can **always** be created. # or # Check the validation of the profile. If it is not valid, then # return false from the callback. Best to use a before_validation # if doing this. View code should check the errors of the child. # Or add the child errors to the User model error array of the :base # error item end end 
0
source

Source: https://habr.com/ru/post/1384051/


All Articles