2

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?

ErmIg
  • 3,980
  • 1
  • 27
  • 40
suhasa
  • 97
  • 1
  • 12
  • That's how it's supposed to work, you don't save the password in the database. it's saved as a digest for security reasons. – trueinViso Feb 21 '17 at 05:49
  • You never save actual password, only digest. This way if your database is hacked, user passwords can't be recovered by hacker to infer other services password. – Maxence Feb 21 '17 at 07:36

1 Answers1

3

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
Shannon
  • 2,988
  • 10
  • 21
  • Thanks Shannon, what if i want to validate for two methods: say "delete" and "create", ":on" doesn't work for two methods. – suhasa Feb 22 '17 at 04:53