如何配置专家以显示属于父债券的项目
How configure pundit to display items belonging to a parent bond
我的用例是,如果用户有角色 :agency
,他可以看到客户。但我必须使用客户和代理机构之间的 link 来验证这一点。看看下面我的代码:
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
谢谢!
这样解决了我的问题。我希望它能帮助别人。
我的模型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
我的用例是,如果用户有角色 :agency
,他可以看到客户。但我必须使用客户和代理机构之间的 link 来验证这一点。看看下面我的代码:
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
谢谢!
这样解决了我的问题。我希望它能帮助别人。
我的模型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