Random password generation for new user on create

I have a user table in my database and what I wish to do is have a
random password generated for each user on create which is then sent to
their email address. I was wondering how I would assign the random

I have the following in my view:

    <div id="p1"><%= t('.username')%></div>
    <%= f.text_field :username %>
    <div id="p1"><%= t('.email')%></div>
    <%= f.text_field :email %>
<p class="button"><%= f.submit 'Create Account' %></p>

The following in my controller:

def create
@user = User.new(params[:user])
respond_to do |format|
   if @user.save
       format.html { redirect_to @user, notice: 'User was successfully
created.' }
       format.json { render json: @user, status: :created, location:
@user }
       format.html { render action: "new" }
       format.json { render json: @user.errors,
status::unprocessable_entity }

And I have the following in my user model:

attr_accessor :password
before_save :encrypt_password

def encrypt_password
    if password.present?
    self.password_salt = BCrypt::Engine.generate_salt
    self.password_hash = BCrypt::Engine.hash_secret(password,

def self.random_string(length=8)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
  password = ''
  length.times { |i| password << chars[rand(chars.length)] }

def self.authenticate(email, password)
    user = find_by_email(email)
    if user && user.password_hash ==
BCrypt::Engine.hash_secret(password, user.password_salt)

I will have to remove my if password.present? line because it won't be
present but I have the random string code, I just need to assign it to
the hash/salt.

I tried changing the following:

  def encrypt_password
    if self.save
      self.password_salt = String.random_string
      self.password_hash = encrypt_password(@password)

But I get a stack too deep error.