我希望根据用户的角色在索引视图上显示不同类型的维基。 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'并得到了'#]>' –