2016-10-19 4 views
0

Мой вариант использования, если у пользователя есть роль :agency, он может видеть клиентов. Но я должен использовать связь между клиентом и агентством, чтобы проверить это. Посмотрите ниже, чтобы увидеть мой код:Как настроить pundit для отображения элементов, принадлежащих к родительской связи

class Agency < ApplicationRecord 
    has_many :agency_clients 
    has_many :clients, through: :agency_clients 

    resourcify 
end 

class AgencyClient < ActiveRecord::Base 
    belongs_to :agency 
    belongs_to :client 
end 

class Client < ApplicationRecord 
    has_many :agency_clients 
    has_many :agencies, through: :agency_clients 

    resourcify 
end 


class ClientPolicy < ApplicationPolicy 
    def show? 
    user.has_role?(:admin) || user.has_role?(:client, record) 
    end 

    class Scope < Scope 
    def resolve 
     if user.has_role? :admin 
     scope.all 
     elsif user.has_role? :client, :any 
     scope.with_role(:client, user) 
     else 
     scope.none 
     end 
    end 
    end 
end 

Thanks!

ответ

0

Этот способ решил мою проблему. Надеюсь, это поможет другим.

Моя модель Agency имеет много Clients:

class Agency < ApplicationRecord 
    has_many :clients 

    resourcify 
end 

Мои User имеют отношения:

class User < ApplicationRecord 
    has_many :users_roles 
    has_many :roles, through: :users_roles 
    has_many :agencies, through: :roles, source: :resource, source_type: 'Agency' 

    rolify 

    ... 
end 

Нужна создать UsersRole модель:

class UsersRole < ApplicationRecord 
    belongs_to :user 
    belongs_to :role 
end 

Наконец, мой ClientPolicy:

class ClientPolicy < ApplicationPolicy 
    def show? 
    user.has_role?(:admin) || user.has_role?(:client, record) 
    end 

    class Scope < Scope 
    def resolve 
     if user.has_role? :admin 
     scope.all 
     elsif user.has_role? :client, :any 
     scope.with_role(:client, user) 
     elsif user.has_role? :agency, :any 
     scope.where(agency_id: user.agencies.pluck(:id)) 
     else 
     scope.none 
     end 
    end 
    end 
end