【发布时间】:2014-08-20 01:59:39
【问题描述】:
我从 RailsApps.org 的 Rails 4.1 Pundit / Devise 应用程序开始,并在用户控制器中调用“授权用户”时继续收到未定义的方法错误。用户可以注册、登录和编辑他们的帐户信息。单击用户链接时,结果如下:
UsersController#index 中的 NoMethodError
# 的未定义方法“授权”
这里是用户控制器...
class UsersController < ApplicationController
before_filter :authenticate_user!
after_action :verify_authorized
def index
@users = User.all
authorize User # <== This is the line the error occurs on
end
def show
@user = User.find(params[:id])
authorize @user
end
def update
@user = User.find(params[:id])
authorize @user
if @user.update_attributes(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
authorize user
user.destroy
redirect_to users_path, :notice => "User deleted."
end
private
def secure_params
params.require(:user).permit(:role)
end
end
还有ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
关于如何解决这个问题的任何想法?
提前致谢!
评论:这是来自 RailsApp Pundit 快速入门指南,用于解释 授权
关键字authorize 是一个辅助方法,它提供了实现实际授权的较长语句的快捷方式。我们从来没有看到完整的语句,因为我们使用了 helper 方法,但是如果我们使用它,它看起来像这样:
引发“未授权”,除非 UserPolicy.new(current_user, User).index?
authorize 辅助方法找到一个 UserPolicy 类并将其实例化,传递 current_user 对象和 User 类或 User 模型的实例,然后调用索引?方法返回真或假。您可能想知道为什么我们可以提供 User 类(如在 index 操作中)或 @user 实例变量(如在 show 操作中)。
当从控制器操作调用授权时,Pundit 会查找策略对象。我们已经看到,如果给出以下任何参数,Pundit 将找到 UserPolicy:
授权用户——用户类
授权@user – 一个实例变量,它是 User 类的一个实例
授权用户——一个简单的变量,它是用户类的一个实例
授权@users - 一组用户对象
对我来说,似乎有时会在 show 和 update 中找到辅助方法,但在 index 中却没有。
【问题讨论】:
标签: ruby-on-rails-4 devise pundit