4

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
1
  • Rails4? You can use has_secure_password in the model if you have a password_digest attribute. Commented Jan 21, 2015 at 20:34

1 Answer 1

5

Use the before_create callback:

class User < ActiveRecord::Base
  before_create :create_password

  private
  def create_password
    self.password = SecureRandom.base64(8)
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.