【问题标题】:Ruby on rails -Devise - Require password to delete accountRuby on rails -Devise - 需要密码才能删除帐户
【发布时间】:2026-01-26 17:45:01
【问题描述】:

目前我的用户需要输入密码才能更改他们的电子邮件地址或密码,但可以在不输入的情况下删除他们的帐户。我不知道如何要求这个。

到目前为止我有:

用户控制器:

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" = $1  [["id", 15]]

如何要求用户输入密码才能删除帐户?

【问题讨论】:

  • 不认识的人@user.destroy_with_password(current_password)

标签: ruby-on-rails devise passwords destroy


【解决方案1】:

您正在调用 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 将返回一个truthy value

【讨论】:

  • 好吧,事情进展顺利,但我收到一条“当前密码无效”消息,即使它是有效的。