ruby-on-railspasswordspassword-hashbcrypt-ruby

Rails- not able to save user's password bcrypt


I have user model and controller, user has password, password_confirmation, and password_digest fields. I have used bcrypt ruby gem.

When I create user, I give all above mentioned fields and user gets created. But User's password wont be saved, it gets saved in the hex form in password_digest field.

If I want to edit just user's name and when I open edit user form, the form has password and password_confirmation fields are empty. I have to again give a new password to save the user which I don't want to.

attr_accessor didn't help.

Here's my user's controller:

   before_filter :authorize

   def create
    @user = User.new(user_params)
    if @user.valid?
     @user.password = params[:user][:password]
     @user.password_confirmation = params[:user][:password_confirmation]
     @user.save!
     redirect_to users_path
    else
     flash[:error] = @user.errors.full_message
     render :new
    end
   end

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

  def update
   @user = User.find(params[:id])
   if @user.update_attributes(user_params)
    redirect_to user_path
   else
    render 'edit'
    flash[:error] = @user.errors.full_messages
   end
  end

  private
  def user_params
   params.require(:user).permit(:first_name, :last_name, :emp_id, :email, :password, :password_confirmation)
  rescue
  {}
  end

Heres my user model:

class User < ApplicationRecord
 rolify
 require 'bcrypt'
 has_secure_password
 # other field validations here....
 validates :password, presence: true
 validates :password_confirmation, presence: true
end

And edit form:

<%#= other fields here..... %>
<%= f.label :Password_for_this_portal %>
<%= f.password_field :password, :class=>"form-control" %>
<%= f.label :Confirm_passsword_for_this_portal %>
<%= f.password_field :password_confirmation, :class=>"form-control" %>
# ..... submit button here

How NOT to ask again for password change in edit user form?


Solution

  • has_secure_password is designed to validate the password and password_digest. However, in Rails 4.x, there is an option to disable the password being validated with:

    class User < ApplicationRecord
      has_secure_password :validations => false
    end
    

    You might be able to perform validations on create only, such as:

     validates :password, presence: true, :on => :create
     validates :password_confirmation, presence: true, :on => :create