ruby on rails -如何允许用户在不提供密码的情况下编辑他们的帐户



我使用Rails 4和设计3.2.4进行身份验证。

我试图让用户更新他们的帐户(例如:名称,电子邮件....等),而无需提供密码。

我遵循这个教程-> https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password

按照教程所说的,我可以不提供密码更新用户,但是当我想要更改"密码"本身时,我不需要提供密码确认和当前密码。

如何允许用户在不提供密码的情况下更改名字、姓氏,并且在更改密码时需要用户输入密码、密码确认和当前密码?

请参阅下面我的代码。

谢谢。<标题> = = = = = 更新

我的代码似乎不工作,如果我有:validatable在我的User Model

<标题> = =

registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
    def update
        account_update_params = devise_parameter_sanitizer.sanitize(:account_update)
        if account_update_params[:password].blank?
           account_update_params.delete("password")
           account_update_params.delete("password_confirmation")
        end
        @user = User.find(current_user.id)
        if @user.update_attributes(devise_parameter_sanitizer.sanitize(:account_update))
           set_flash_message :notice, :updated
           sign_in @user, :bypass => true
           redirect_to @user
        else
            render "edit"
        end
    end
protected
end

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) { |u|
      u.permit(:firstname, :lastname, :password, :password_confirmation )}
  end
end

用下面的代码替换注册控制器

class RegistrationsController < Devise::RegistrationsController
  def update
    @user = User.find(current_user.id)
    successfully_updated = if needs_password?(@user, params)
      @user.update_with_password(devise_parameter_sanitizer.sanitize(:account_update))
    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(devise_parameter_sanitizer.sanitize(:account_update))
    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
  end
  private
  # check if we need password to update user data
  # ie if password or email was changed
  # extend this as needed
  def needs_password?(user, params)
    user.email != params[:user][:email] ||
      params[:user][:password].present?
  end
end

使用此代码,您将需要在更改密码和电子邮件时输入密码,而在更改任何其他信息时不需要密码

相关内容

最新更新