Updating `User` attributes without requiring password

steffi2392 picture steffi2392 · Aug 16, 2011 · Viewed 17.2k times · Source

Right now, users can edit some their attributes without having to enter their password because my validations are set up like this:

validates :password, :presence =>true, :confirmation => true, :length => { :within => 6..40 }, :on => :create
validates :password, :confirmation => true, :length => { :within => 6..40 }, :on => :update, :unless => lambda{ |user| user.password.blank? } 

However, after a user does this, their password is deleted - update_attributes is updating their password to "". Here is my update definition:

def update

    if @user.update_attributes(params[:user])
        flash[:success] = "Edit Successful."
        redirect_to @user
    else
        @title = "Edit user"
        render 'edit'
    end
end

I've also tried using a different definition that uses update_attribute instead:

def save_ff
    @user = User.find(params[:id])
    @user.update_attribute(:course1, params[:user][:course1] )
    @user.update_attribute(:course2, params[:user][:course2] )
    @user.update_attribute(:course3, params[:user][:course3] )
    @user.update_attribute(:course4, params[:user][:course4] )
    redirect_to @user 
end 

But for some reason this is doing the same thing. How can I update some user attributes without changing the password? Thanks!

Answer

apneadiving picture apneadiving · Aug 17, 2011

I didn't realize the solution I gave you yesterday would lead to this problem. Sorry.

Well, taking inspiration from devise, you should simply update your controller this way:

def update
  params[:user].delete(:password) if params[:user][:password].blank?
  if @user.update_attributes(params[:user])
    flash[:success] = "Edit Successful."
    redirect_to @user
  else
    @title = "Edit user"
    render 'edit'
  end
end