在我的Pundit策略中使用范围(Rails 5)

问题描述 投票:0回答:1

如何在我的Pundit策略中使用模型中定义的范围?

在我的模型中,我有一个范围:

scope :published, ->{ where.not(published_at: nil )}

在我的Pundit政策中,我有

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
ruby-on-rails ruby-on-rails-5 pundit
1个回答
0
投票

范围是类方法,您无法在实例上调用它们。

您还必须定义published?实例方法:

def published?
  published_at.present?
end

如果您询问给定范围内的记录是否存在,您可以使用范围:

User.published.exists?(user.id)

如果范围包含用户ID,它将返回true,但我不建议这样做,它需要对数据库进行额外查询,以便从您已有的用户实例中获取可以知道的内容。

© www.soinside.com 2019 - 2024. All rights reserved.