ruby-on-rails - 在我的 Pundit 政策中使用范围(Rails 5)
问题描述
如何在我的 Pundit 政策中使用模型中定义的范围?
在我的模型中,我有一个范围:
scope :published, ->{ where.not(published_at: nil )}
在我的权威政策中,我有
class CompanyPolicy < ApplicationPolicy
def index?
true
end
def create?
user.present?
end
def new?
true
end
def show?
true
end
def update?
user.present? && user == record.user
end
end
如何在 Pundit 政策中使用我的范围?我只想在它“已发布”时展示它,像这样,目前不起作用:
class CompanyPolicy < ApplicationPolicy
def show
record.published?
end
end
解决方案
范围是类方法,您不能在实例上调用它们。
您还必须定义一个published?
实例方法:
def published?
published_at.present?
end
如果您询问记录是否存在于给定范围内,则可以使用范围:
User.published.exists?(user.id)
如果范围包括用户 ID,它将返回 true,但我不建议这样做,它需要对数据库进行额外查询才能从已有的用户实例中获取一些信息。
推荐阅读
- c# - 如何在 Web Api 中创建基本身份验证?
- javascript - 每次交互的形式重新生成,角度形式
- cakephp-2.3 - CakePHP 2.3 中的路由
- jquery - Jquery pickadate同时打开和关闭
- c++ - 如何在 C 中将 32 位有符号整数值转换为等效的 64 位有符号整数
- java - JNA loadLibrary() 方法显示带有参数的错误
- json - 使用 JsonSlurper 解析多个 json 的最佳方法
- javascript - Wordpress 主题在链接上阻止 target="_blank"。如何为某些外部链接重新激活它?
- spring-batch - 嵌套异常是 java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist - 如何避免创建 Spring Batch 元数据?
- bash - 使用文本文件中的外部变量自动执行 curl 脚本