I have this code in my user model
class User < ActiveRecord::Base
after_create :set_user_full_name
.........
private
def set_user_full_name
self.name = "Test name"
end
end
But when I create a user the name attribute is nil. I tried adding name to
create and update strong params but no luck.
devise_parameter_sanitizer.for(:sign_up) << [:name]
devise_parameter_sanitizer.for(:account_update) << [:name]
Any help would be appreciated!
after_create
callback is executed after inserting user data in db.
in your code, name
is not actually inserted.
user = User.create(some_attiributes)
user.name #=> "Test name"
user.reload
user.name #=> nil
If you want to insert name attribute, use before_create
callback.
It assign name value before insert
Updated:
If User has first_name
and last_name
attribute,
before_create :set_user_full_name
def set_user_full_name
self.name = "#{first_name} #{last_name}"
end
But If User does not have first_name
and last_name
attribute, you should handle in controller.
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :set_name_param, only: [:create]
private
def set_name_param
params[:user][:name] = "#{params[:user][:first_name]} #{params[:user][:last_name]}"
end
end