0

I want to change my User model's profile attribute which is just a string in a form_for. I am running into a problem where my password is getting set to blank when I update my profile attribute.

That is, my user account has a password, but when I change my profile, my password becomes blank. The next time I try to log in, I just leave the password field blank.

How do I change my profile field without changing my password?

Thanks.

Here is my form below and update action. I'm passing a hidden field called updating_password which is a boolean for whether or not password validation and confirmation is required.

edit_profile.html.erb

<%= form_for @user, :html => { :multipart => true } do |f| %>

  <%= f.label :profile %>
  <%= f.text_area :profile%>

  <%= f.hidden_field :updating_password, :value => "false" %>

  <%= submit_tag "update" %>

<% end %>

users_controller.rb

def update
  @user = User.find(params[:id])
  @user.updating_password = params[:user][:updating_password]

  #for updating profile only
  if(@user.updating_password == 'false')
    if @user.update_attribute('profile', params[:user][:profile])
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
     end
   end

  #for updating everything else including password
  if(@user.updating_password == 'true')
    if @user.update_attributes(params[:user])
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
    end
  end
end

I'll add the relevant updating_password snippet from my user.rb file:

validates_presence_of :password, :if => :should_validate_password?
validates_confirmation_of :password, :if => :should_validate_password?

  def should_validate_password?
    updating_password || new_record?
  end
Huy
  • 10,806
  • 13
  • 55
  • 99
  • 2
    What authentication framework are you using? Devise, for example, saves the password encrypted as `encrypted_password`, and the normal, unencrypted `password` field remains blank except during the process of it being set or changed. – Russell May 12 '12 at 19:50
  • @Russell I didn't use any framework. You are correct though, I found my solution at this post http://stackoverflow.com/a/8790881/1154722 My model now has `before_save :encrypt_password, :unless => Proc.new { |u| u.password.blank? }` and it works. – Huy May 12 '12 at 19:55

0 Answers0