I've been working through the Ruby on Rails Tutorial by Michael Hartl. Currently, in order to edit any of the User attributes, the user must confirm their password. Is there any way to update the user attributes without having to do this?
My form looks like this:
<%= form_for @user do |f| %>
<div class="field">
<%= f.label :course1 %><br />
<%= f.text_field :course1 %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>"
and my update definition in users_controller.rb looks like this:
def update
if @user.update_attributes(params[:user])
flash[:success] = "Edit Successful."
redirect_to @user
else
@title = "Edit user"
render 'edit'
end
end
Currently, the update_attributes action fails.
Thanks!
On your User
model, you probably have something along the lines of:
validates_presence_of :password_confirmation
Add an if
clause as follows, that way it only checks for the confirmation when the password is actually being changed:
validates_presence_of :password_confirmation, :if => :password_changed?
To slightly refine Dylan's answer, you need to define that password_changed method which was giving you the error. I used a different name, as I don't care if the password has been changed.
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 },
:unless => :already_has_password?
private
def already_has_password?
!self.encrypted_password.blank?
end
If you are using bcrypt to encrypt the password, here is the code that worked for me on Rails 4
#--Code for User method
validates :password, presence: true, confirmation: true, :unless => :already_has_password?
#
private
def already_has_password?
!self.password_digest.blank?
end
来源:https://stackoverflow.com/questions/7073720/ruby-on-rails-tutorial-how-to-edit-user-information-without-confirming-the-pass