[英]Pundit Scoping for Model Ownership through a Join table - Rails 4
我要通過聯接表將用戶與給定的公司相關聯,因為我需要能夠在每個公司中擁有大量用戶,反之亦然。
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
我是否需要在公司級別創建一個接受@user的范圍? 還是我可以直接直接內聯? 我可以一起砍東西,但還沒有把我的頭纏住專家,所以任何方向都將不勝感激!
像這樣:
def self.associated_with(user)
all.select { |m| m.users.include?(user) }
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
該策略並不一定總是以您的思維方式來調用它,它只需要返回某些內容(對於范圍,幾乎始終是ActiveRecord :: Relation,對於常規,true或false而言)。 你可以做
scope.includes(:firm_connections).where(firm_connections: { user_id: user.id })
但這不是可讀性(IMO)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.