4

Lets say if i want to generate and set default password for user while creating them in admin.

and i want to do something like this,

 def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password=> @default_generated_password, :password_confirmation => @default_generated_password)
end

I am using sorcery for User Authentication. I am having a feeling that this is completely wrong way, But how do i do it?

suyesh
  • 530
  • 7
  • 23

2 Answers2

5

You want to use reverse_merge (appeared in rails 5.1) or with_defaults (alias appeared in rails 5.2)

def user_params
  params
      .require(:user)
      .permit(:first_name, :last_name, :email, :password, :password_confirmation)
      .with_defaults(password: @default_generated_password, password_confirmation: @default_generated_password)
end
Astery
  • 1,216
  • 13
  • 22
1

Merge them in after

params
 .require(:user)
 .permit(:first_name, :last_name)
 .merge(password: @default_generated_password, password_confirmation: @default_generated_password)

Or if you need it just in one action (create for example)

def create
  # password generation code...
  # ...

  @user = User.new(user_params.merge(password: @default_generated_password, password_confirmation: @default_generated_password))

  if @user.save
   redirect_to ...
  else
   flash[:error] = "Did not save"
   render :new
  end
end

private 

def user_params
  params.require(:user).permit(:first_name, :last_name)
end
patkoperwas
  • 1,341
  • 10
  • 14
  • 3
    This should not be marked as the correct answer. If we have two hashes `a` and `b`, `a.merge(b)` will return a new hash with all the elements in `b` plus the elements that are only defined in `a` [reference](https://apidock.com/ruby/Hash/merge). This means that the result hash will **always** contain `password: @default_generated_password, password_confirmation: @default_generated_password` even if `params` contains those keys. – Perennialista Jul 28 '20 at 20:13