Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create random password when creating new user with Rails

I would like to use @value = SecureRandom.base64(8) to set the password filed when I create a new user only. I don't want it to happened when I edit the user. So my question is where do I use the SecureRandom.base64(8) in the users_controller.rb or the models/user.rb

This is the users_controller.rb

def create
    if user.save
      user.send_invitation
      redirect_to root_url, notice: "Signed up!"
    else
      render :new
    end
  end

  def destroy
    @user = User.find(params[:id])

    if @user.destroy
        redirect_to root_url, notice: "User was deleted successfully!"
    end
  end

  def edit
    respond_with(user)
  end

  def update
    @user.password_confirmation = User.value
    params[:user].delete(:password) if params[:user][:password].blank?
    params[:user].delete(:password_confirmation) if params[:user][:password_confirmation].blank?
    if user.save
      redirect_to users_path, :notice => "Saved your updates!"
    else
      render :edit
    end
  end
like image 446
Raz Avatar asked Oct 19 '25 13:10

Raz


1 Answers

Use the before_create callback:

class User < ActiveRecord::Base
  before_create :create_password

  private
  def create_password
    self.password = SecureRandom.base64(8)
  end
end
like image 84
Rodrigo Avatar answered Oct 22 '25 03:10

Rodrigo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!