以管理员身份访问用户编辑页面



目前,我在用户控制器中的编辑动作是这样的:

  def edit
    @user = User.find(params[:id])
  end

如果我想访问我自己的用户配置文件,则此操作有效。但是,如果我想访问其他人的用户配置文件,这将不起作用。我该如何改变这一点?

添加一个before动作check_right_user,检查当前用户是否试图访问自己的配置文件。

before_action :check_admin, only: [:edit, :update, :destroy]

def check_admin
  unless current_user.admin?
    redirect_to root_path, alert: "You're not authorized"
  end
end

我假设您在application_controllerusers_controller中定义了current_user方法,并在user模型中定义了admin字段。

最新更新