Mysql 通过联接表对模型所有权进行Pundit范围界定-Rails 4
我通过一个联接表将用户与给定的公司关联起来,因为我需要能够让每个公司都有一组用户,反之亦然Mysql 通过联接表对模型所有权进行Pundit范围界定-Rails 4,mysql,ruby-on-rails,ruby,join,pundit,Mysql,Ruby On Rails,Ruby,Join,Pundit,我通过一个联接表将用户与给定的公司关联起来,因为我需要能够让每个公司都有一组用户,反之亦然 class User has_many :firm_connections, dependent: :destroy has_many :firms, through: :firm_connections end class FirmConnection belongs_to :user belongs_to :firm end class Firm has_many :firm_
class User
has_many :firm_connections, dependent: :destroy
has_many :firms, through: :firm_connections
end
class FirmConnection
belongs_to :user
belongs_to :firm
end
class Firm
has_many :firm_connections
has_many :users, through: :firm_connections
end
我的问题是,当一个用户点击公司的索引页面时,我如何确定它的范围以只显示那些用户与什么相关
class FirmPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin?
scope.all
else
scope.where #only the firms associated with that user
end
end
end
这应该对你有用
class Firm
def index
@firms = policy_scope(Firm)
end
end
class FirmPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin?
scope.all
else
user.firms #only the firms associated with that user
end
end
end
end
但在我看来,这并不那么容易理解
class Firm
def index
@firms = policy_scope(Firm)
end
end
class FirmPolicy < ApplicationPolicy
class Scope < Scope
def resolve
if user.admin?
scope.all
else
user.firms #only the firms associated with that user
end
end
end
end
scope.includes(:firm_connections).where(firm_connections: { user_id: user.id })