简体   繁体   中英

ActiveAdmin - Edit Devise user without changing password

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?

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.

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  

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM