首页 > 解决方案 > 查看时如何授权单个属性

问题描述

希望能够授权某些用户能够查看字段,而不仅仅是对整个对象有限制

标签: ruby-on-railspundit

解决方案


作为文档的一部分,试图帮助您:

使用 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

推荐阅读