在我的 Pundit 政策中使用范围 (Rails 5)
Using scopes in my Pundit policy (Rails 5)
如何在我的 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 政策中使用我的范围?我想仅在它是 "published" 时显示它,像这样的东西,目前不起作用:
class CompanyPolicy < ApplicationPolicy
def show
record.published?
end
end
范围是 Class 方法,您不能在实例上调用它们。
你也必须定义一个 published?
实例方法:
def published?
published_at.present?
end
如果您询问记录是否存在于给定范围内,您可以使用该范围:
User.published.exists?(user.id)
如果范围包含用户 ID,它将 return 为真,但我不建议这样做,它需要对数据库进行额外查询才能从用户实例中获取一些信息已经有了。
如何在我的 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 政策中使用我的范围?我想仅在它是 "published" 时显示它,像这样的东西,目前不起作用:
class CompanyPolicy < ApplicationPolicy
def show
record.published?
end
end
范围是 Class 方法,您不能在实例上调用它们。
你也必须定义一个 published?
实例方法:
def published?
published_at.present?
end
如果您询问记录是否存在于给定范围内,您可以使用该范围:
User.published.exists?(user.id)
如果范围包含用户 ID,它将 return 为真,但我不建议这样做,它需要对数据库进行额外查询才能从用户实例中获取一些信息已经有了。