我正在尝试为三个角色创建一个显示视图。管理员、超级用户和用户。管理员应该看到所有用户。超级用户应该只看到用户,用户不应该看到任何人。当我在 resolve for 中使用注释掉的策略方法时else user.super_user?
会给我unsupported: TrueClass
错误。欢迎任何建议。
用户控制器
def index
@users = policy_scope(User)
authorize User
end
用户政策
class UserPolicy
attr_reader :current_user, :model
def initialize(current_user, model)
@current_user = current_user
@user = model
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.admin?
scope.all
else user.super_user?
scope.where(user.role = 'user' )
# scope.where(user.role != 'admin') [this would not work in the views, but it would work in rails c]
end
end
end
def index?
@current_user.admin? or @current_user.super_user?
end
end
更新 的用户控制器
class UsersController < ApplicationController
before_filter :authenticate_user!
after_action :verify_authorized
def index
@users = policy_scope(User)
end
end
正确答案
我想出了我需要做什么。我错误地调用了这个角色。更新范围如下。
class UserPolicy
attr_reader :current_user, :model
def initialize(current_user, model)
@current_user = current_user
@user = model
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.admin?
scope.all
else user.super_user?
scope.where(role: 'user' )
end
end
end
def index?
@current_user.admin? or @current_user.super_user?
end
控制器
class UsersController < ApplicationController
before_filter :authenticate_user!
after_action :verify_authorized
def index
@users = policy_scope(User)
authorize @users
end