【问题标题】:How to get all documents and hide this which are expired if they are defined?如果已定义,如何获取所有文档并隐藏已过期的文档?
【发布时间】:2014-06-01 21:15:03
【问题描述】:

如果定义了过去的事件,我想隐藏它们并获取所有其他事件。即使 :once_at 为 nil 并且如果 :once_at 已定义然后隐藏这些过期的文档,如何显示所有文档?

我最近的方法,只显示定义了 :once_at 的事件,(我尝试使用 :once_at => nil,但没有结果):

default_scope where(:once_at.gte => Date.today)

或(也不起作用)

default_scope excludes(:once_at.lte => Date.today)

【问题讨论】:

    标签: ruby-on-rails mongoid mongoid3


    【解决方案1】:

    你认为Date.today 什么时候被评估?如果你这样说:

    default_scope where(:once_at.gte => Date.today)
    

    Date.today 将在加载类时进行评估。这几乎不是您想要发生的事情,您通常希望在使用默认范围时评估 Date.today,而实现这种情况的通常方法是使用 proc 或 lambda 作为范围:

    default_scope -> { where(:once_at.gte => Date.today) }
    

    下一个问题是如何处理没有:once_at:once_at 中具有显式nil 的文档。 nil 不会大于今天,因此您最好使用 :$or 查询单独检查您的条件:

    default_scope -> do
      where(
        :$or => [
          { :once_at     => nil        },
          { :once_at.gte => Date.today }
        ]
      )
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 2021-04-01
      • 2019-12-15
      • 1970-01-01
      相关资源
      最近更新 更多