【问题标题】:Custom Update Function for Devise. Requiring current password only when updating password设计的自定义更新功能。仅在更新密码时需要当前密码
【发布时间】:2014-09-19 14:28:54
【问题描述】:

我目前有一个用户具有额外的属性,我希望他们能够在不输入当前密码的情况下进行更新。

所以我必须创建自己的 RegistrationsController 并覆盖更新方法。 (取自 Devise github 页面)。

  def update
    account_update_params = devise_parameter_sanitizer.sanitize(:account_update)

    # required for settings form to submit when password is left blank
    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(account_update_params)

      set_flash_message :notice, :updated

      # Sign in the user bypassing validation in case their password changed
      sign_in @user, :bypass => true
      redirect_to edit_user_registration_path

    else
      render 'edit'
    end
  end

但是现在,如果他们想更改密码,我想要求他们输入正确的当前密码。这似乎是一个问题,因为如果他们确实输入了当前密码,我必须将其添加到允许的参数中。但是它告诉我 current_password 不是用户的有效属性。

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :attr1, :attr2,
                                                                   :password, :password_confirmation) }
  end

【问题讨论】:

    标签: ruby-on-rails ruby devise


    【解决方案1】:

    使用update_with_passwordupdate_without_password mehotds

    with_password = params[:current_password].present?
    
    if @user.update_user(with_password)
    
      set_flash_message :notice, :updated
    
      # Sign in the user bypassing validation in case their password changed
      sign_in @user, :bypass => true
      redirect_to edit_user_registration_path
    
    else
      render 'edit'
    end
    
    private 
    def update_user(with_password)
      if with_password
        @user.update_with_passoword(account_update_params)
      else
        @user.update_passoword(account_update_params)
      end
    end
    

    documentation

    【讨论】:

    • 当我尝试使用“update_with_password”时,我收到一条消息,告诉我当前密码不能为空。我没有在我的用户模型中验证它的存在,我应该在哪里改变它?
    • 好的。我会编辑答案,但基本上。当您提供密码 (current_password) 以确认用户凭据时。当您在没有 current_password 的情况下进行更新时,您可以使用 update_withou_password 方法。
    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2012-06-22
    • 2023-03-31
    相关资源
    最近更新 更多