Rails 4 - Pundit - scoped policy for index

后端 未结 3 1236
萌比男神i
萌比男神i 2021-01-14 17:24

I am trying to learn how to use Pundit with my Rails 4 app.

I have the following models:

class User < ActiveRecord::Base
  has_one :profile
  has_         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-14 18:23

    I'm the previous commenter on that issue.

    For your EoiScope, you simply want what Eois the user has access to (because they belong to projects under this profile), independent from the project (this requirement is only for the controller, because is nested), so your controller should look something like this:

    Edit: Based on your latest attempt, I've updated the scope to account for Eois belonging directly to the user (not through a project) and you should simply scope it to a project or not based on the presence of params[:project_id], see updated answer.

    @eois = policy_scope(Eoi)
    @eois = @eios.where(project_id: params[:project_id]) if params[:project_id]
    

    And your scope should do joins until it reaches user or simply look for the user_id property on Eoi.

      class EoiPolicy < ApplicationPolicy
        class Scope < Scope
          def resolve
            scope.joins(project: : profile).where 'profiles.user_id = ? OR eois.user_id = ?', user.id, user.id
          end
        end
    
        # Other methods that differ from ApplicationPolicy's methods
      end
    

    Please note, Scope isn't calling eoi, but default* scope only knows about scope and user. * By default, I mean when it inherits from ApplicationPolicy::Scope

提交回复
热议问题