6

I try to do that. Unfortunately I have problems with overriding update and I don't know how to do that correctly. The way I do that in another place is:

if params[:user][:password].blank?
  params[:user].delete("password")
  params[:user].delete("password_confirmation")
end
# ...
user.save!

So I tried to override update

def update
  if params[:user][:password].blank?
    params[:user].delete("password")
    params[:user].delete("password_confirmation")
  end
  super
end

But it doesn't works. I still get can't be blank near to the password input. How to achieve expected behaviour?

ciembor
  • 7,189
  • 13
  • 59
  • 100

3 Answers3

17

I take the answer of @anonymousxxx and add the following:

If you're using rails admin, you can override the controller "User" as follows:

#app/admin/user.rb
controller do
  def update
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
      params[:user].delete("password")
      params[:user].delete("password_confirmation")
    end
    super
  end
end

You should also note that, if you have the User model validations, specify when such validations are applied, for example:

validates :name, :email, presence: true
validates :password, :password_confirmation, presence: true, on: :create
validates :password, confirmation: true

This allows me to validate password presence only when I create a new user and update without changing his password.

I hope this is helpful.

calrrox
  • 329
  • 4
  • 8
  • Instead of adding `validates` to the model to make the field not required, you can also use the following in the `form do |f|` block in `app/admin/users.rb`: `f.input :password, required: f.object.new_record?` – Jan Schär Mar 19 '21 at 22:25
12

Add this code to your user model. This will do the trick for you.

# User.rb

private    
def password_required?
  new_record? ? super : false
end  
Amal Kumar S
  • 15,555
  • 19
  • 56
  • 88
  • 4
    Should be flagged as the answer – phyzalis Jun 23 '15 at 12:28
  • Be aware that this has side-effects in regards to the password confirmation field. When a user wants to change his password for example then the password_confirmation field is not required anymore.. – Bijan Sep 14 '18 at 13:40
0

This is works for me :

def update
     @user = User.find(current_user.id)
     params[:user].delete(:current_password)
     if @user.update_without_password(params[:user])
       redirect_to ....
     else
       render ....
     end
end

or

def update
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
        params[:user].delete(:password)
        params[:user].delete(:password_confirmation)
    end
    super
end

source

Community
  • 1
  • 1
rails_id
  • 8,120
  • 4
  • 46
  • 84
  • My solution works too, after removal of `validates :password, :presence => true`. I assume, that Device's validations are enough. – ciembor May 17 '13 at 14:04