问题
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
来源:https://stackoverflow.com/questions/10566865/how-to-only-change-one-attribute-in-a-model-using-form-for-in-rails