Ruby rails -设计 - 需要密码才能删除帐户

Ruby on rails -Devise - Require password to delete account

目前我的用户需要输入密码才能更改他们的电子邮件地址或密码,但无需输入即可删除他们的帐户。我不确定如何要求这个。

到目前为止我有:

用户控制器:

def destroy
    @user = User.find(current_user.id)
    @user.destroy_with_password(user_params)
      if @user.destroy
          redirect_to root_url, notice: "User deleted."
      else
        redirect_to users_url
        flash[:notice] = "Couldn't delete"
      end
    end



    def user_params
         params.require(:user).permit(:username, :email, :password,
                                      :password_confirmation, :current_password, :avatar, etc....etc.... )
    end

一个表格:

<%= simple_form_for(@user, :method => :delete) do |f| %>
      <%= f.input :current_password, autocomplete: "off" %>
      <%= f.button :submit %>
<% end %>

此处用户不输入密码也删除。正确的控制器操作正在处理删除请求;

Processing by UsersController#destroy as HTML

Processing by UsersController#destroy as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"bla bla bla", "user"=>{"current_password"=>"[FILTERED]"}, "commit"=>"Update User", "locale"=>"en", "id"=>"ce2dc2edc"}

SQL (0.1ms)  DELETE FROM "users" WHERE "users"."id" =   [["id", 15]]

如何才能要求用户提供密码才能删除帐户?

您正在调用 Devise 的 destroy_with_password ,然后调用 ActiveRecord 的 destroy。你只需要调用destroy_with_password。代码应如下所示:

def destroy
  @user = User.find(current_user.id)
  if @user.destroy_with_password(user_params)
  # if @user.destroy      # <== remove me, don't need to destroy twice!
      redirect_to root_url, notice: "User deleted."
  else
    redirect_to users_url
    flash[:notice] = "Couldn't delete"
  end
end

destroy_with_password 将要 return 一个 truthy value