加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 5 – 如何使用Pundit

发布时间:2020-12-17 02:09:25 所属栏目:百科 来源:网络整理
导读:在我努力学习如何在我的rails app中使用pundit的过程中,我已经有了很长的休息时间.我回来了,并试图学习如何使用专家. 我已经制作了一个全新的rails 5 app并安装了专家. 我有一个用户资源,一个应用程序策略和一个用户策略.每个人都有: 用户控制器: def inde
在我努力学习如何在我的rails app中使用pundit的过程中,我已经有了很长的休息时间.我回来了,并试图学习如何使用专家.

我已经制作了一个全新的rails 5 app并安装了专家.

我有一个用户资源,一个应用程序策略和一个用户策略.每个人都有:

用户控制器:

def index
    # @users = User.all
    @users = policy_scope(User)
  end

申请政策

class ApplicationPolicy
  attr_reader :user,:record

  def initialize(user,record)
    @user = user
    @record = record
  end

  def index?
    true
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(user,record.class)
  end

  class Scope
    attr_reader :user,:scope

    def initialize(user,scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

用户政策

class UserPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.where(user: user)
    end
  end


end

然后在我的用户索引中,我试图按照权威宝石文档中的说明进行操作:

<% policy_scope(@users).each do |user| %>

我收到此错误:

PG::UndefinedColumn: ERROR:  column users.user does not exist
LINE 1: SELECT "users".* FROM "users" WHERE "users"."user" = '566119...
                                            ^
: SELECT "users".* FROM "users" WHERE "users"."user" = '566119d2-54d8-4ab2-b7c5-f17c80b517f3' AND "users"."user" = '566119d2-54d8-4ab2-b7c5-f17c80b517f3'

任何人都可以看到我是如何开始错误的吗?我甚至没有尝试以我想要的方式定义我的范围,但它现在不起作用.

解决方法

class UserPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.where(user: user)
    end
  end
end

scope.where表示User类(user.where),因为它在用户策略中.

用户值是当前用户,由应用程序范围继承.

您发布的范围示例我猜测您只想显示当前用户记录.然后您可以执行以下注释:

scope.where(id: user.try(:id))

另外,因为您已在控制器中定义了范围

def index
  # @users = User.all
  @users = policy_scope(User)
end

您无需在视图中定义另一个.

<% policy_scope(@users).each do |user| %>

这是一个或另一个.在视图中你可以简单地做用户.做….

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读