问题
I'm using Omniauth to allow users to sign in (and create an account) through Facebook, Twitter, and Google.
However, if a user decides to not use those services anymore, but continue to use their account, they will want to add a password.
How can I let a user add a password to their account without entering a current password
?*
When I let a user go to the edit_user_registration_path(@user)
, they see the form below:
= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put, name: 'validation'}) do |f|
= devise_error_messages!
= f.label :email, class: 'block'
= f.email_field :email, class: 'large'
%span.infobar Keep this here unless you'd like to change your email
= f.label :password, class: 'block'
= f.password_field :password, class: 'large'
%span.infobar Leave blank if you don't want to change it
= f.label :password_confirmation, class: 'block'
= f.password_field :password_confirmation, class: 'large'
- if @user.password_required?
= f.label :current_password, class: 'block'
= f.password_field :current_password, class: 'large'
%span.infobar We need your current password to confirm changes
= f.submit "Update"
user.rb
def password_required?
(authentications.empty? || !password.blank?) && super
end
As you can see, I have it so that if @user.password_required?
, then show the current password field. Even though this field is not displayed when attempting to create a new password for the account, the form will not validate correctly, as a current password is required.
回答1:
I just overwrote the RegistrationsController#update method:
class RegistrationsController < Devise::RegistrationsController
def update
# Override Devise to use update_attributes instead of update_with_password.
# This is the only change we make.
if resource.update_attributes(params[resource_name])
set_flash_message :notice, :updated
# Line below required if using Devise >= 1.2.0
sign_in resource_name, resource, :bypass => true
redirect_to after_update_path_for(resource)
else
clean_up_passwords(resource)
render_with_scope :edit
end
end
end
Source: How To: Allow users to edit their account without providing a password
来源:https://stackoverflow.com/questions/9022131/rails-3-2-omniauth-devise-add-password-skip-current-password