gpt4 book ai didi

ruby-on-rails - Pundit 范围界定,如何让成员只能看到他们的帖子?

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:34 24 4
gpt4 key购买 nike

我正在为我的学校作业授权,这是一个 Reddit 克隆。我刚刚被介绍给 Pundit Gem,用于对用户角色进行授权,即管理员、版主、成员和访客。

我必须这样做:

Admins and Moderators should see all posts, members should only see their own posts, and guests should see no posts.

Sign in as a normal user, and you should only see the posts you've created.

application_policy.rb

class ApplicationPolicy
attr_reader :user, :record

def initialize(user, record)
@user = user
@record = record
end

def index?
false
end

def show?
scope.where(:id => record.id).exists?
end

def create?
# Checks if user exists and is logged in
user.present?
end

def new?
create?
end

def update?
# Checks if user is logged in, the owner or admin
user.present? && (record.user == user || user.admin?)
end

def edit?
update?
end

def destroy?
update?
end

def scope
record.class
end
end

这是我正在做的事情:

这将检查用户是否存在,以及用户是否是版主或管理员,并且只授予他们查看帖子的权限。就像说明状态一样工作。

post_policy.rb

class PostPolicy < ApplicationPolicy
def index?
user.present? && (user.moderator? || user.admin?)
end
end

现在,如果我回头看看我的 application_policy.rb,我可以在这里看到这一行,“检查用户是否登录、所有者或管理员”:

user.preset? && (record.user == user || user.admin?)

如果我尝试将此添加到我的索引授权中?我会继续得到一个

"NoMethodError in PostsController#index"

class PostPolicy < ApplicationPolicy
def index?
user.present? && (user.moderator? || user.admin? || record.user == user)
end
end

谢谢。

最佳答案

使用范围:https://github.com/elabs/pundit#scopes

在您的情况下,PostPolicy.rb 应该如下所示:

class PostPolicy < ApplicationPolicy
def index?
true
end

class Scope
attr_reader :user, :scope

def initialize(user, scope)
@user = user
@scope = scope
end

def resolve
if user.admin? || user.moderator?
scope.all
else
scope.where(user: user)
end
end

end

end

关于ruby-on-rails - Pundit 范围界定,如何让成员只能看到他们的帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29993444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com