问题
I executed following code
@user = User.find(current_user.id)
successfully_updated = if needs_password?(@user, params)
@user.update_with_password(params[:user])
else
# remove the virtual current_password attribute update_without_password
# doesn't know how to ignore it
params[:user].delete(:current_password)
@user.update_without_password(params[:user])
end
if successfully_updated
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end
but update_without_password give false
and database is rollbacked.
Do I have to do something for update_without_password?
回答1:
I just went through my own issues with this. The following code should work as advertised (as found on the wiki page for Devise).
def update
@user = User.find(current_user.id)
successfully_updated = if needs_password?(@user, params)
@user.update_with_password(params[:user])
else
params[:user].delete(:current_password)
@user.update_without_password(params[:user])
end
if successfully_updated
set_flash_message :notice, :updated
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end
end
Make sure you also define the private method for 'needs_password?'
def needs_password?(user, params)
(params[:user].has_key?(:email) && user.email != params[:user][:email])
|| !params[:user][:password].blank?
end
My issue was that I had removed the "email" field from the form in the 'edit.html.erb' file, so the 'needs_password?' method kept returning true since user.email was never equal to nil. To fix the issue, I added in a check params[:user].has_key?(:email)
to see if 'email' exists in the hash.
FWIW, the 'update_without_password' pretty much works the same way as 'update_with_password' except that it strips out the 'password' and 'password_confirmation' parameters before calling 'update_attributes' on the object, so you shouldn't have to do anything more. Try looking upstream a bit and see if you really are calling 'update_without_password'.
来源:https://stackoverflow.com/questions/15405598/railsupdate-without-password-doesnt-update-user-info