ruby-on-rails - 查看时如何授权单个属性
问题描述
希望能够授权某些用户能够查看字段,而不仅仅是对整个对象有限制
解决方案
作为文档的一部分,试图帮助您:
使用 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
推荐阅读
- c# - 具有属性的singelton类的依赖注入
- python - 有没有一种技术可以分析时间序列集群之间的关系?
- c++ - llvm 的 dyn_cast 是否仍用作 dynamic_cast 的替代品?
- php - 以编程方式创建的产品未显示在商店页面上
- c++ - (C++)当我按顺序遍历树时,发生运行时错误
- c - 我试图在 c 编程中使用哈希解决 leetcode 中的 2 和问题
- reactjs - 如何从 React.js 中的另一个 js 文件切换
- android-intent - Android中的隐式意图或显式意图
- swift - 在 json swift 5 中获取图像字符串的问题
- jquery - 当数据返回 AJAX 时,如何在按钮上启动 Bootstrap Spinner 并返回原始状态?