【发布时间】:2019-07-09 21:58:53
【问题描述】:
希望能够授权某些用户拥有查看字段的能力,而不仅仅是对整个对象有限制
【问题讨论】:
-
欢迎来到 Stackoverflow。这不是一个好问题,请参阅here 它应该是什么样子。请修改您的问题并添加示例。
标签: ruby-on-rails pundit
希望能够授权某些用户拥有查看字段的能力,而不仅仅是对整个对象有限制
【问题讨论】:
标签: ruby-on-rails pundit
试图帮助你,作为文档的一部分:
使用 Pundit,您可以通过您的策略控制用户有权更新哪些属性。您可以像这样在策略中设置 allowed_attributes 方法:
# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
def permitted_attributes
if user.admin? || user.owner_of?(post)
[:title, :body, :tag_list]
else
[:tag_list]
end
end
end
还有一个助手可以控制每个操作的权限
permitted_attributes(record, action = action_name) 可以代替。
或者,很可能,您想使用定义访问某些属性的范围。
来自有关范围的文档:
通常,您会希望查看特定用户有权访问的某种查看列表记录。使用 Pundit 时,您需要定义一个称为策略范围的类。它可能看起来像这样:
class PostPolicy < ApplicationPolicy
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
if user.admin?
scope.all
else
scope.where(published: true)
end
end
end
def update?
user.admin? or not record.published?
end
end
【讨论】: