【发布时间】:2023-03-21 00:35:01
【问题描述】:
我希望根据用户的角色在索引视图中显示不同类型的 wiki。 admin 和 standard / 来宾用户的政策可以正常工作,但对于高级用户和协作,它会变得有点混乱。在我的应用程序中,我可以将协作者添加到私人 Wikis 。因此,高级用户我应该能够看到我正在合作的我的私人 wiki、公共 wiki 和私人 wiki,但我的合作者所在的私人 wiki 并没有显示给我。这可能与我的政策或我的模特协会有关吗?请帮帮我
wiki#index
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
....
维基模型
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
维基政策
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 分配给您正在使用的协作者,因为当您以标准用户身份登录时它正在工作。代码看起来不应该失败
-
我在我使用的控制台上测试了它:
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">]>
标签: ruby-on-rails policy pundit bloc.io