我希望根據用戶的角色在索引視圖上顯示不同類型的維基。 admin
和standard
/guest用戶的政策應該像它應該的那樣工作,但是當涉及到高級用戶和協作時,它會變得有點混亂。在我的應用程序中,我可以添加合作者到私人Wikis
。因此,一個高級用戶我應該能夠看到我的私人維基,公共維基和私人維基,但是在合作者沒有爲我顯示的私人維基上。它可能與我的政策或我的模型關聯有關嗎?請幫我Pundit政策:Wiki未向合作伙伴展示
維基#指數
def index
@wikis = Kaminari.paginate_array(policy_scope(Wiki)).page(params[:page]).per(10)
end
用戶模型
class User < ActiveRecord::Base
has_many :wikis
has_many :collaborators
belongs_to :collaborators
....
wiki模式
class Wiki < ActiveRecord::Base
belongs_to :user
has_many :collaborators
has_many :users, through: :collaborators
....
合作者模型
class Collaborator < ActiveRecord::Base
belongs_to :user
belongs_to :wiki
end
Wiki_policy
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
wikis = []
if user.role == 'admin'
wikis = scope.all # if the user is an admin, show them all the wikis
elsif user.role == 'premium'
all_wikis = scope.all
all_wikis.each do |wiki|
if wiki.private == false || wiki.owner == user || wiki.collaborators.include?(user)
wikis << wiki # if the user is premium, only show them public wikis, or that private wikis they created, or private wikis they are a collaborator on
end
end
else # this is the lowly standard user
all_wikis = scope.all
wikis = []
all_wikis.each do |wiki|
if wiki.private == false || wiki.collaborators.include?(user)
wikis << wiki # only show standard users public wikis and private wikis they are a collaborator on
end
end
end
wikis # return the wikis array we've built up
end
end
,當我去到控制檯
last = Wiki.last
last.collaborators
我得到這個:
=> #<ActiveRecord::Associations::CollectionProxy [#<Collaborator id: 7, user_id: 8, wiki_id: 104, created_at: "2016-04-24 08:07:20", updated_at: "2016-04-24 08:07:20">]>
嘗試在控制檯手動測試代碼。我懷疑你實際上沒有將wiki分配給你使用的協作者,因爲它以標準用戶身份登錄時正在工作。代碼看起來不像應該失敗 – joewoodward
我在控制檯上測試了它:'last = Wiki.last,last.collaborators'並得到了'#]>' –