具有以下记录条件的 Activerecord 查询

Activerecord query with condition on following record

我有一个 Event 模型,开始日期有一个 starts 属性。一个事件在下一个事件开始时结束(最后一个事件无限期地进行)。我想查询 returns 从包含给定日期 dd:

的事件开始的事件
Event.since(Date.today)

应该return当前事件和后续事件。

我可以通过两个查询轻松做到这一点:

first=Event.where(starts: -Float::INFINITY..Date.today).order(starts: :asc).last
Event.where(starts: first.starts..Float::INFINITY)

但是有什么更有效的方法吗?

这是 postgresql,以防有差异

class Event < ApplicationRecord
  # @see https://devhints.io/arel
  def self.after(time = Time.current)
    col = arel_table[:starts]
    sub_query = arel_table.project(col)
                          .where(col.lt(time))
                          .order(col.asc)
                          .take(1)
    where(col.gt(sub_query))
  end
end

这会在 where 子句中生成一个子查询:

SELECT "events".* FROM "events" 
WHERE "events"."starts" > (SELECT "events"."starts" FROM "events" WHERE "events"."starts" < '2020-03-08 17:32:16.602529' ORDER BY "events"."starts" ASC LIMIT 1) LIMIT