如何在我的专家策略中使用模型中定义的作用域?
在我的模型中我有一个作用域:
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
我如何在专家政策中使用我的范围?我只想在它“发布”的情况下展示它,就像这样,目前不起作用:
class CompanyPolicy < ApplicationPolicy
def show
record.published?
end
end
发布于 2018-09-09 22:31:01
作用域是类方法,你不能在实例上调用它们。
您还必须定义一个published?
实例方法:
def published?
published_at.present?
end
如果您使用以下命令询问记录是否存在于给定的作用域中,则可以使用作用域:
User.published.exists?(user.id)
如果作用域包含用户id,它将返回true,但我不建议这样做,因为它需要对数据库进行额外的查询,才能从已有的user实例中获得一些信息。
https://stackoverflow.com/questions/52245219
复制相似问题