1

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!

fardin
  • 1,399
  • 4
  • 16
  • 27

1 Answers1

3

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
Jaehyun Shin
  • 1,562
  • 14
  • 25
  • thanks that actually woked. However, I have `firstname` and `lastname` attributes in sign up form and my plan is to join the two to become the `name` attribute. How should I do that? Thanks a lot again :) – fardin Jan 09 '16 at 12:42
  • 1
    I updated answer! it is rough code, kinda concept for understanding. – Jaehyun Shin Jan 09 '16 at 12:50