【问题标题】:How to use Pundit policy for two different models?如何将 Pundit 政策用于两种不同的模型?
【发布时间】:2019-11-11 21:57:28
【问题描述】:

我有三个模型。

用户

has_many :projects

项目

has_many :users

网站

belongs_to :project
has_many :users

我还使用 Active Admin 和 Pundit 来管理我的项目和权限。如果网站的项目也是用户的项目,我需要控制用户访问网站对象。

为此我准备了这样的代码;

scope.where("#{@record.project.id.in? Project.where(id: ProjectUser.where(user_id: @user.id).ids).ids}")

但它返回错误消息:

nil:NilClass 的未定义方法 `project'

我该如何解决这个问题?

【问题讨论】:

  • 它说@record 是 nil,首先看看为什么它是 nil。很难说,因为您只显示一行代码而没有上下文。

标签: ruby-on-rails pundit ruby-on-rails-6


【解决方案1】:

我找到了解决办法。

class Scope < Scope
 def resolve
   case @user.class.to_s
   when 'AdminUser'
     scope.all
   when 'User'
     project_user_array = ProjectUser.where(user_id: @user.id)
     project_ids = project_user_array.map {|object| object[:project_id] }
     scope.where(project_id: project_ids)
   end
 end
end

【讨论】:

    【解决方案2】:

    用户has_many :projects - 它为您提供project_ids 用户实例的方法。就用它吧:

    scope.where(project_id: @user.project_ids)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多