Pundit 范围已发布但未过期日期条件

Pundit scope published but not expired date condition

如果我只想return 已发布但未过期的提案,Pundit 可以吗?

到目前为止,我有这个:

class ProposalPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      if @user.admin?
        scope.all
      else
        scope.where(published: true)
      end
    end
  end

  ...

end

一种解决方法是在我的提案控制器的 index 操作中编写额外的代码,以进一步过滤提案实例列表,只包含未过期的提案。

我希望有像这样的神奇语法:

scope.where({published: true, expire_date > Time.now })

有什么想法吗? :D

其实有,你可以做

范围 .where(发布:真) .where("expire_date > ? ",Time.now)

您可以在单个 where 命令中执行此操作:

scope.where('published = ? AND expire_date > ?', true, Time.now)

或者,一分为二:

scope.where(published: true)
     .where('expire_date > ?', Time.now)

至于这个逻辑应该走向何方,由你决定。

如果这确实是政策的限制(即只有管理员允许查看expired/unpublished提案),那么把它放在 Pundit 范围内。

另一方面,如果非管理员只是为了方便显示过滤列表(但仍然可以通过其他方式查看 expired/unpublished 提案),那么我宁愿把这个查询放在控制器中。