我创建了一种删除用户的方法。检查的实质是用户只能删除其帐户,或者管理员可以执行此操作。但是,当您尝试删除该用户的帐户时,将 pop 错误“您对此没有权限”
def destroy
if @user.present? && (current_user.id == @user.id || current_user.admin?)
@user.destroy
respond_to do |format|
format.html { redirect_to root_path, notice: t(:destroy) }
end
else
respond_to do |format|
format.html { redirect_to root_path, notice: t(:permission_error) }
end
end
end
最佳答案
确实,解决此问题的方法是使用before_action
作为操作的开头(或使用Pundit而不是重新发明轮子),这样您就不会在整个地方复制授权逻辑。
# app/errors/authorization_error.rb
class AuthorizationError < StandardError; end
class ApplicationController < ActionController::Base
rescue_from 'AuthorizationError', with: :deny_access
private
def deny_access
respond_to do |format|
format.html { redirect_to root_path, notice: t(:permission_error) }
format.json { head :unauthorized }
end
end
end
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :authorize_user!, only: [:edit, :update, :destroy]
def destroy
# much dry - such wow
@user.destroy
respond_to do |format|
format.html { redirect_to root_path, notice: t(:destroy) }
end
end
private
def set_user
# Don't worry - this will raise an error if the user is not found
@user = User.find(params[:id])
end
def authorize_user!
unless @user == current_user || current_user.admin?
raise AuthorizationError
end
end
end
关于ruby-on-rails - 在删除用户方法中传递条件时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60987672/